我几个小时后面临一个问题...
我有这种类型的json:
{
"datas": {
"General": [
{
"field": "hotel_name",
"maxlength": "15"
},
{
"field": "logo",
"maxlength": "0"
}
],
"Rooms": [
{
"field": "room_1",
"maxlength": "15"
},
{
"field": "room_2",
"maxlength": "15"
},
{
"field": "room_3",
"maxlength": "15"
}
]
}
}
我想在这个json中循环以便打印:
所以我试过了:
<?php
// copy file content into a string var
$json_file = file_get_contents('datas.json');
// convert the string to a json object
$jfo = json_decode($json_file);
// copy the posts array to a php var
$datas = $jfo->datas;
foreach ($datas as $data) {
echo $data[0];
}
?>
但没有印刷......
请帮忙吗?
感谢。
答案 0 :(得分:0)
为第二级使用另一个循环,您需要获取显示第一级标题的键。示例中用粗略的html来说明所需的输出:
foreach ($datas as $name => $data) {
echo "<ul><li>$name<ul>";
foreach($data as $room) {
echo "<li>{$room->field}</li>";
}
echo "</ul></li></ul>";
}