使用PHP解析JSON文件

时间:2022-07-20 15:25:30

I have been given a JSON file that I need to parse. I am doing some work for a hotel, and the end goal is to build a table that lists:

我收到了一个需要解析的JSON文件。我正在为一家酒店做一些工作,最终目标是建立一个表格列出:

Room Number
Adult Content (enabled or disabled)
Room Charges (enabled or disabled)
Status (occupied or unoccupied)

The JSON file, I have no control over. It is given to me, and from there I have to create the layout noted above.

JSON文件,我无法控制。它给了我,从那里我必须创建上面提到的布局。

This is an example of the JSON file I am given (it is only part of the file, but you will understand how it works from this sample):

这是我给出的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"

What I have done thus far:

到目前为止我做了什么:

I have tried to parse the data, and I can get the data to display, however, I am having trouble laying it out exactly the way I need it to look as stated above. Currently, my parse script outputs this:

我试图解析数据,并且我可以显示数据,但是,我很难按照我上面所述的方式进行显示。目前,我的解析脚本输出:

data
roomCount: 105 

rooms
0
room_number: 104 

services
0
adult
enabled: 1 

room_charges
enabled: 1 

status: OCCUPIED 

I need it to NOT display the key for the nested array, "Services." What I would like as I said above is for the output to look like this:

我需要它不显示嵌套数组的键,“服务”。我上面所说的是输出看起来像这样:

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

And finally, here is the code that I have completed so far:

最后,这是我到目前为止完成的代码:

<?php
$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 "<br> $key";
    } else {
        echo "<br> $key: $val <br>";
    }
}

?>

I am looking for some refinement on outputting the data in a cleaner way. If you can help or give me any suggestions/advice I will greatly appreciate it.

我正在寻找一些更清晰的输出数据的改进。如果您能提供帮助或给我任何建议/意见,我将不胜感激。

3 个解决方案

#1


2  

Here is json decoded as Object

这里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;

Tested and here is an output

经测试,这是一个输出

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
----

#2


1  

Basically you just need to check if the keys and values are set:

基本上你只需要检查是否设置了键和值:

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key=>$value) {
    if($key === 'room_number') {
        echo "Room Number: " . $value . "<br />";
    }
    if($key === 'adult') {
        echo "Adult: " . $value['enabled'] . "<br />";
    }
    if($key === 'status') {
        echo "status: " . $value . "<br />";
    }
}

#3


1  

For illustrational purposes you could just use a table or a description list on this case. The UI is up to you:

出于说明目的,您可以在此案例中使用表格或说明列表。用户界面取决于您:

<?php

$response = '{ "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 = json_decode($response, true);

?>

<style type="text/css">/*DL, DT, DD TAGS LIST DATA*/dl { margin-bottom:50px;} dl dt { background:#5f9be3; color:#fff; float:left; font-weight:bold; margin-right:10px; padding:5px; width:150px; } dl dd { margin:2px 0; padding:5px 0;}</style>
<dl>
<?php foreach($data['data']['rooms'] as $info): ?>
    <dt>Room Number: </dt>
    <dd><?php echo $info['room_number']; ?></dd>
    <?php $services = reset($info['services']); ?>
    <dt>Adult: </dt>
    <dd><?php echo ($services['adult']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></dd>
    <dt>Room Charges: </dt>
    <dd><?php echo ($services['room_charges']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></dd>
    <dt>Status: </dt>
    <dd><?php echo $info['status']; ?></dd><br/>
<?php endforeach; ?>
</dl>

#1


2  

Here is json decoded as Object

这里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;

Tested and here is an output

经测试,这是一个输出

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
----

#2


1  

Basically you just need to check if the keys and values are set:

基本上你只需要检查是否设置了键和值:

$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key=>$value) {
    if($key === 'room_number') {
        echo "Room Number: " . $value . "<br />";
    }
    if($key === 'adult') {
        echo "Adult: " . $value['enabled'] . "<br />";
    }
    if($key === 'status') {
        echo "status: " . $value . "<br />";
    }
}

#3


1  

For illustrational purposes you could just use a table or a description list on this case. The UI is up to you:

出于说明目的,您可以在此案例中使用表格或说明列表。用户界面取决于您:

<?php

$response = '{ "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 = json_decode($response, true);

?>

<style type="text/css">/*DL, DT, DD TAGS LIST DATA*/dl { margin-bottom:50px;} dl dt { background:#5f9be3; color:#fff; float:left; font-weight:bold; margin-right:10px; padding:5px; width:150px; } dl dd { margin:2px 0; padding:5px 0;}</style>
<dl>
<?php foreach($data['data']['rooms'] as $info): ?>
    <dt>Room Number: </dt>
    <dd><?php echo $info['room_number']; ?></dd>
    <?php $services = reset($info['services']); ?>
    <dt>Adult: </dt>
    <dd><?php echo ($services['adult']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></dd>
    <dt>Room Charges: </dt>
    <dd><?php echo ($services['room_charges']['enabled'] == 1) ? 'ENABLED' : 'DISABLED'; ?></dd>
    <dt>Status: </dt>
    <dd><?php echo $info['status']; ?></dd><br/>
<?php endforeach; ?>
</dl>