Foreach through JSON stdClass Object array in PHP

530 Views Asked by At

I am fetching a JSON api in PHP, then I am attempting to iterate through the array with a foreach($obj['result'] as $c) loop. I'm specifically trying to loop through the [result] nested array, but the returned stdClass Object is not letting me do it. I have attempted to use $obj = get_object_vars($obj) but that doesn't seem to work for the $obj['result'] lower nested array. Any ideas what I do here to foreach through the $obj['result'] ?

$json = file_get_contents($rink);
$obj = array();
$obj = json_decode($json);

When I use php print_r() I get.

stdClass Object (
[status] => 1
[message] => OK
[result] => Array
    (
        [0] => stdClass Object
            (
                [blockNumber] => 10271028
                [timeStamp] => 1646413513
                [hash] => 0xab6f7d30aec4f...
            )

        [1] => stdClass Object
            (
                [blockNumber] => 10271028
                [timeStamp] => 1646413513
                [hash] => 0xab6f7d30aec4f...
            )
    )
)

Php foreach attempted loop

foreach($obj['result'] as $c) {
    echo $c['hash'] . '<br>';
}
1

There are 1 best solutions below

2
Shoyeb Sheikh On

Change

foreach($obj['result'] as $c) {
    echo $c['hash'] . '<br>';
}

to

foreach($obj->result as $c) {
    echo $c->hash . '<br>';
}

Object key value is accessed with -> operator in php.