我收到了一个需要解析的JSON文件.我正在为一家酒店做一些工作,最终目标是建立一个表格列出:
Room Number
Adult Content (enabled or disabled)
Room Charges (enabled or disabled)
Status (occupied or unoccupied)
JSON文件,我无法控制.它是给我的,从那里我必须创建上面提到的布局.
这是我给出的JSON文件的一个示例(它只是文件的一部分,但您将从此示例中了解它是如何工作的):
{
"apiVersion" : "0.1",
"data" : {
"roomCount" : 105,
"rooms" : [
{
"room_number" : "104",
"services" : [
{
"adult" : {
"enabled" : true
},
"room_charges" : {
"enabled" : true
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "105",
"services" : [
{
"adult" : {
"enabled" : true
},
"room_charges" : {
"enabled" : false
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "106",
"services" : [
{
"adult" : {
"enabled" : false
},
"room_charges" : {
"enabled" : true
}
}
],
"status" : "OCCUPIED"
},
{
"room_number" : "107",
"services" : [
{
"adult" : {
"enabled" : false
},
"room_charges" : {
"enabled" : false
}
}
],
"status" : "OCCUPIED"
到目前为止我做了什么:
我试图解析数据,我可以显示数据,但是,我无法按照我上面所述的方式完成它的显示方式.目前,我的解析脚本输出:
data
roomCount: 105
rooms
0
room_number: 104
services
0
adult
enabled: 1
room_charges
enabled: 1
status: OCCUPIED
我需要它不显示嵌套数组的键,“服务”.正如我上面所说,我想要的是输出看起来像这样:
Room Number: 104
Adult: Enabled or Disabled (depending on true or false)
Room Charges: Enabled or Disabled (depending on true or false)
Status: OCCUPIED or UNOCCUPIED
最后,这是我到目前为止完成的代码:
$string = file_get_contents("test.json");
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($string, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "
$key";
} else {
echo "
$key: $val
";
}
}
?>
我正在寻找一些更清晰的输出数据的改进.如果您能提供帮助或给我任何建议/意见,我将非常感激.
解决方法:
这里json解码为Object
$arr = json_decode($jsonString);
$out = "";
foreach ($arr->data->rooms as $k => $v) {
$adult = $v->services[0]->adult->enabled == 'true' ? 'Enabled' : 'Disabled';
$room = $v->services[0]->room_charges->enabled == 'true' ? 'Enabled' : 'Disabled';
$out .="Room Number: $v->room_number\n";
$out .="Adult: $adult\n";
$out .="Room Charges: $room\n";
$out .="Status: $v->status\n";
$out .= "----\n";
}
echo $out;
经测试,这是一个输出
Room Number: 104
Adult: Enabled
Room Charges: Enabled
Status: OCCUPIED
----
Room Number: 105
Adult: Enabled
Room Charges: Disabled
Status: OCCUPIED
----
Room Number: 106
Adult: Disabled
Room Charges: Enabled
Status: OCCUPIED
----
标签:json,php,arrays
来源: https://codeday.me/bug/20190624/1277131.html