0

I have a json and want to convert it to a table with all the values from the json source. This is a small part of the json:

 [sport_events] => Array
    (
        [0] => stdClass Object
            (
                [id] => sr:match:14972279
                [scheduled] => 2018-10-11T17:00:00+00:00
                [start_time_tbd] => 
                [status] => not_started
                [tournament_round] => stdClass Object
                    (
                        [type] => group
                        [number] => 1
                        [group] => A
                    )

I have this code which loops the json and gets me nicely the first level values (ie. id,scheduled,start_time_tbd,status) from all the sport_events:

<?php
    $json=file_get_contents("json_url");
    $data =  json_decode($json);
    if (count($data->sport_events)) {
        // Open the table
        echo "<table>";
        // Cycle through the array
        foreach ($data->sport_events as $idx => $sport_events) {
            // Output a row
            echo "<tr>";
            echo "<td>$sport_events->id</td>";
            echo "<td>$sport_events->scheduled</td>";
            echo "<td>$sport_events->start_time_tbd</td>";
            echo "<td>$sport_events->status</td>";
            echo "</tr>";
        }
        // Close the table
        echo "</table>";
    }
?>

How can I change my code to get the nested values as well (ie. type,number and group from tournament_round)?

Thanks!

Miggy
  • 816
  • 7
  • 16
vasilis smyrnios
  • 105
  • 1
  • 1
  • 6

1 Answers1

2
<?php
$json=file_get_contents("json_url");
$data =  json_decode($json);
if (count($data->sport_events)) {
    // Open the table
    echo "<table>";
    // Cycle through the array
    foreach ($data->sport_events as $idx => $sport_events) {
        // Output a row
        echo "<tr>";
        echo "<td>$sport_events->id</td>";
        echo "<td>$sport_events->scheduled</td>";
        echo "<td>$sport_events->start_time_tbd</td>";
        echo "<td>$sport_events->status</td>";
        echo "</tr>";
        foreach($sport_events->tournament_round as $tournament) {
           echo $tournament->type;
           echo $tournament->number;
           echo $tournament->group;
        }
    }
    // Close the table
    echo "</table>";
}
Saeed M.
  • 2,216
  • 4
  • 23
  • 47