Php cannot use stdClass object as array

Derp. Getting "Fatal error: you cannot use an object of type stdClass as an array"

I don't know what I'm doing wrong here:

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; } } 

And here is the data:

 [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 ) ) ) 

Essentially, I'm trying to check if there is an array of cannot_trade attributes. Sometimes the parent does not have an 'attributes' object

+4
source share
2 answers

You can parse your JSON as an array if you want:

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

You can try

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

If it still does not work, try adding

 var_dump($val); 

in a loop to check what it really contains.

+1
source

Source: https://habr.com/ru/post/1346262/


All Articles