循环使用json对象以使用PHP解析水平行

时间:2015-10-30 14:25:12

标签: php json

我只是对如何处理这种情况感到困惑。

我是这个看起来像这样的JSON

[
{
    "date":"oct10",
    "number_x": "100",
    "number_y": "200",
    "number_z": "300"
},
{
    "date":"oct11",
    "number_x": "300",
    "number_y": "600",
    "number_z": "200"
},
{
    "date":"oct13",
    "number_x": "200",
    "number_y": "660",
    "number_z": "230"
}
]

我正在努力实现类似的输出。

<table>
    <tr>
        <td>"date":"oct10"</td>
        <td>"date":"oct11"</td>
        <td>"date":"oct12"</td>
    </tr>
    <tr>
        <td>"number_x": "100",</td>
        <td>"number_x": "300",</td>
        <td>"number_x": "200",</td>
    </tr>
    <tr>
        <td>"number_y": "200",</td>
        <td>"number_y": "600",</td>
        <td>"number_y": "660",</td>
    </tr>
    <tr>
        <td>"number_z": "300",</td>
        <td>"number_z": "200",</td>
        <td>"number_z": "230",</td>
    </tr>
</table>

任何帮助或起点都将不胜感激!谢谢你的阅读。

1 个答案:

答案 0 :(得分:1)

下面的代码将解析json字符串,然后构建一些额外的数组以便转移数据。

它将根据需要输出。

$jsonStr = '[
{
    "date":"oct10",
    "number_x": "100",
    "number_y": "200",
    "number_z": "300"
},
{
    "date":"oct11",
    "number_x": "300",
    "number_y": "600",
    "number_z": "200"
},
{
    "date":"oct13",
    "number_x": "200",
    "number_y": "660",
    "number_z": "230"
}
]';

$obj = json_decode($jsonStr);

foreach($obj as $row){
    $date[] = $row->date;
    $x[] = $row->number_x;
    $y[] = $row->number_y;
    $z[] = $row->number_z;

}

print '<table>' . 
    '<tr><td>' . implode('</td><td>Date: ',$date) . '</td></tr>' . 
    '<tr><td>' . implode('</td><td>Number X : ',$x) . '</td></tr>' . 
    '<tr><td>' . implode('</td><td>Number Y : ',$y) . '</td></tr>' . 
    '<tr><td>' . implode('</td><td>Number X : ',$z) . '</td></tr>' . 
    '</table>';