Rashed Uddin Ripon
Rashed Uddin Ripon

Reputation: 9

Accessing JSON array data in PHP

I am trying to get some data from an external API. From the JSON data I want to retrieve some data as marked in the image.

enter image description here

I can access the "teams" data by using this code -

foreach( $data->data as $info ) {
            echo '<li class="team-1">'. $info->teams[0].'</li>';
            echo '<li class="team-2">'. $info->teams[1].'</li>';
 };

But when I try to access data more deep from array of objects it doesn't work & gives me error -

foreach( $info->sites as $site) {
        foreach( $site->odds as $odd) {
            echo $odd->h2h[0];
        }
}

So my question is what is the best way to loop through the data to access these arrays. I am using this code in Wordpress but I think it will be same as PHP.

Upvotes: 0

Views: 5943

Answers (3)

HU is Sebastian
HU is Sebastian

Reputation: 101

You get this json from an external api and convert it using json_decode, right? If that is so, just use the second parameter "$assoc" and set it to true to not get an object, but an associative array that you can use like this:

$info = json_decode($api_answer,true);
if(isset($info['sites']['odds'])){
     foreach($info['sites']['odds'] as $odd){
        echo $odd['h2h'][0]
     }
}

Upvotes: 0

Los
Los

Reputation: 1

It looks like odds is an object rather than an array.

If h2h will always be the only property in odds then you can try:

foreach( $info->sites as $site) {
    echo $site->odds->h2h[0];
}

Alternatively, if h2h will not always be the only property in odds, then you may want to try casting it into an array:

foreach( $info->sites as $site) {
    foreach( (array)$site->odds as $odd) {
        echo $odd[0];
    }
}

Upvotes: 0

Roberto Maldonado
Roberto Maldonado

Reputation: 1595

You should access h2h directly from odds, since it's not an array, but an object

foreach( $info->sites as $site) {
        echo $site->odds->h2h[0];
}

Upvotes: 1

Related Questions