Ronald van der Meer Ronald van der Meer - 2 months ago 8
PHP Question

How to get a value from an array key within an stdClass Object

I'm building a php webapp and I want to get a list of id's from an array named $array.

stdClass Object
(
[users] => Array
(
[0] => stdClass Object
(
[id] => 90379747
[id_str] => 90379747
)
[1] => stdClass Object
(
[id] => 30207605
[id_str] => 30207605
)
)
)


However when I try to get the value from the id key it somehow is not working.

echo "<h1>Result</h1>";

foreach ($array as $obj)
{
echo $obj->id;
}


What am I doing wrong here. Other examples on stackoverflow seem to suggest this should work.

Answer

You iterate an object, not an array. Try this way:

foreach ($array->users as $obj)
{
  echo $obj->id;
}
Comments