警告:PHP 5.4 中的非法字符串偏移
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16264115/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning: Illegal string offset in PHP 5.4
提问by Henrik Petterson
I upgraded to PHP 5.4 today and I am receiving some strange warnings:
我今天升级到 PHP 5.4,但收到了一些奇怪的警告:
Warning: Illegal string offset 'quote1' in file.php on line 110
Warning: Illegal string offset 'quote1_title' in file.php on line 111
Those lines are this part of the code:
这些行是代码的这一部分:
for($i = 0; $i < 3; $i++) {
$tmp_url = $meta['quote'. ($i+1)];
$tmp_title = $meta['quote' . ($i+1) .'_title'];
if(!empty($tmp_url) || !empty($tmp_title)) {
$quotes[$src_cnt] = array();
$quotes[$src_cnt]['url'] = $tmp_url;
$quotes[$src_cnt]['title'] = $tmp_title;
$src_cnt++;
}
}
So the $tmp_url
and $tmp_title
line.
所以$tmp_url
和$tmp_title
线。
Why am I receiving this odd warning and what is the solution?
为什么我会收到这个奇怪的警告,解决方案是什么?
Update:
更新:
This code is being used as a Wordpress plugin. $meta includes:
此代码被用作 Wordpress 插件。$meta 包括:
$meta = get_post_meta($post->ID,'_quote_source',TRUE);
So I am suspecting that whenever the quotes fields are empty, this warning appears. Is there any way that I can fix this for when the fields are empty?
所以我怀疑每当引号字段为空时,就会出现此警告。当字段为空时,有什么方法可以解决这个问题?
回答by MatthiasLaug
You need to make sure, that $meta
is actually of type array. The warning explicitly tells you, that $meta
seems to be a string
?and not an array
您需要确保它$meta
实际上是数组类型。警告明确告诉您,这$meta
似乎是string
? 而不是array
Illegal string offset
^^^^^^
To avoid this error you may also check for the needed fields
为避免此错误,您还可以检查所需的字段
for($i = 0; $i < 3; $i++) {
if ( !is_array($meta) || !array_key_exists('quote'. ($i+1), $meta) ){
continue;
}
// your code
}
回答by álvaro González
If $meta
is null
whenever there's no data to process:
如果$meta
是null
,每当有没有数据对过程:
if( !is_null($meta) ){
for($i = 0; $i < 3; $i++) {
// ...
}
}
You should be able to do more checks if necessary. That depends on what that get_post_meta()
function is designed to return.
如有必要,您应该能够进行更多检查。这取决于该get_post_meta()
函数旨在返回的内容。