php - 如何修复此非法偏移类型错误

2022-08-30 07:32:38

我得到

非法偏移类型

此代码的每次迭代时出错。代码如下:

$s = array();
for($i = 0; $i < 20; $i++){
    $source = $xml->entry[$i]->source;
    $s[$source] += 1;    
}

print_r($s)

答案 1

当您尝试使用对象或数组作为索引键访问数组索引时,会发生非法偏移类型错误。

例:

$x = new stdClass();
$arr = array();
echo $arr[$x];
//illegal offset type

您的数组包含一个对象或数组 at 的某个值,当您尝试将其用作 的索引键时,您会收到该警告。您必须确保包含您想要的内容,并且正确访问它。$xml$xml->entry[$i]->source$i$s$xml


答案 2

在 之前使用。trim($source)$s[$source]