0

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.

1
  • 1
    Based on the structure you have you should be able to use $site->odds->h2h[0] and $site->odds->h2h[1] Commented Oct 4, 2018 at 0:23

3 Answers 3

1

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];
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.