警告:PHP 5.4中的字符串偏移量非法 [英] Warning: Illegal string offset in PHP 5.4
问题描述
我今天升级到PHP 5.4,并且收到一些奇怪的警告:
I upgraded to PHP 5.4 today and I am receiving some strange warnings:
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++;
}
}
所以$tmp_url
和$tmp_title
行.
为什么我会收到这个奇怪的警告,如何解决?
Why am I receiving this odd warning and what is the solution?
更新:
此代码被用作Wordpress插件. $ meta包括:
This code is being used as a Wordpress plugin. $meta includes:
$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?
推荐答案
您需要确保$meta
实际上是数组类型.该警告明确告诉您,$meta
似乎是string
而不是array
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
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
}
这篇关于警告:PHP 5.4中的字符串偏移量非法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!