Php无法将stdClass对象用作数组

4

出现“Fatal error: Cannot use object of type stdClass as array”错误。

我不知道我的做法哪里出错了:

foreach ($json->result->items[$key]->attributes->attribute as $attrib => $val) 
{
    if($json->result->items[$key]->attributes->attribute[$attrib]->name == 'cannot_trade')
    {
        $notrade=1;
        echo 'Item ' . $key . ' is not tradeable' . $br;
    }
}

以下是数据:

[attributes] => stdClass Object
(
  [attribute] => Array
  (
    [0] => stdClass Object
    (
      [name] => custom employee number
      [class] => set_employee_number
      [value] => 0
    )
    [1] => stdClass Object
    (
      [name] => cannot trade
      [class] => cannot_trade
      [value] => 1
    )
  )
)

本质上,我正在尝试测试“属性”数组是否具有无法交易的内容。有时,父对象没有“属性”对象。


你好,欢迎来到StackOverflow!如果你的问题已经解决,请同时发布解决方案,以便其他人受益。 - Piskvor left the building
哪个访问引起了错误? - Matt Wonlaw
2个回答

9

如果您希望,您可以将您的JSON解析为数组:

// These both give you an array:
$json = json_decode($whatever, true);
$json = (array) json_decode($whatever);

1

你可以尝试一下

if($val->name == 'cannot_trade')
{
    $notrade=1;
    echo 'Item ' . $key . ' is not tradeable' . $br;
}

如果它仍然没有发挥作用,请尝试添加。
var_dump($val);

在循环中,检查它实际包含的内容。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接