首页 > 解决方案 > 通过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 并很好地从所有运动事件中获取第一级值(即 id、scheduled、start_time_tbd、status):

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

如何更改我的代码以获取嵌套值(即来自锦标赛轮次的类型、数字和组)?

谢谢!

标签: phpjson

解决方案


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

推荐阅读