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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2732451/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 07:30:47  来源:igfitidea点击:

php - How do I fix this illegal offset type error

phparrays

提问by Steven

I'm getting

我越来越

illegal offset type

非法偏移类型

error for every iteration of this code. Here's the code :

此代码的每次迭代都会出错。这是代码:

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

print_r($s)

回答by zombat

Illegal offset typeerrors occur when you attempt to access an array index using an objector an arrayas the index key.

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

Example:

例子:

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

Your $xmlarray contains an object or array at $xml->entry[$i]->sourcefor some value of $i, and when you try to use that as an index key for $s, you get that warning. You'll have to make sure $xmlcontains what you want it to and that you're accessing it correctly.

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

回答by Zafer

Use trim($source)before $s[$source].

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

回答by brian_d

check $xml->entry[$i] exists and is an object before trying to get a property of it

在尝试获取它的属性之前检查 $xml->entry[$i] 是否存在并且是一个对象

 if(isset($xml->entry[$i]) && is_object($xml->entry[$i])){
   $source = $xml->entry[$i]->source;          
   $s[$source] += 1;
 }

or $source might not be a legal array offset but an array, object, resource or possibly null

或 $source 可能不是合法的数组偏移量,而是数组、对象、资源或可能为 null

回答by Byron Whitlock

There are probably less than 20 entries in your xml.

您的 xml 中的条目可能少于 20 个。

change the code to this

把代码改成这样

for ($i=0;$i< sizeof($xml->entry); $i++)
...

回答by user8387356

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

我有一个类似的问题。当我从我的 XML 孩子那里得到一个字符时,我必须先将它转换为字符串(或整数,如果你期望的话)。下面显示了我是如何解决这个问题的。

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }