嵌套JSON通过PHP表

时间:2018-07-20 08:49:51

标签: php json

我有一个json,并希望将其转换为包含json源中所有值的表。这只是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
                    )

我有这段代码,它循环了json,并从所有sport_events中很好地获取了我的第一级值(即id,已调度,start_time_tbd,状态):

<?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>";
    }
?>

如何更改代码以获取嵌套值(即Tournat_round中的类型,数字和组)?

谢谢!

1 个答案:

答案 0 :(得分: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>";
}