访问JSON运算符数组中的数组

时间:2019-07-14 03:11:38

标签: php json

我正在尝试访问“气候”键。我可以访问“ UnitFeatures”运算符之外的所有项目。

mainloop

我已经能够使用关联数组进行访问。我还有一个for循环,它将信息输出到表中。

"Location": {     
     "Units": [
               {
                     "BonusComments": "THIS IS A BONUS DEAL",
                     "CubicFootage": 125,
                     "OrderGrouping": "0000001CONTAINER",
                     "SquareFootage": 25,
                     "TotalUnits": 45,
                     "UnitFeature": {
                          "Access": "",
                          "Climate": "NON-CLIMATE",
                          "Doors": "",
                          "Elevation": "OUTSIDE",
                          "Floor": "1",
                          "Product": "CONTAINER"
                          },
                   },
                 ]
               }

我已经尝试了以下行,其中包括:在每种可能的配置中都是$ units [$ i] [“ UnitFeature”] [“ Climate”]。

输出应为“非气候”或“气候”。

2 个答案:

答案 0 :(得分:2)

查看API documentation之后,看来UnitFeature对象是可选的,并且可以为null。因此,代码需要对此进行测试:

foreach ($units as $u) {
    if($u["SquareFootage"]<=100) {
        $temp .= "<tr>";
        $temp .= "<td id='row'>" . $u["UnitSize"] . "</td>";
        if (isset($u["UnitFeature"]["Climate"])) {
            $temp .= "<td id='row'>" . $u["UnitFeature"]["Climate"] . "</td>";
        } else {
            $temp .= "<td id='row'></td>";
        }
        $temp .= "<td id='row'>" . $u["SquareFootage"] . "</td>";
        $temp .= "<td id='row'>" . $u["VacantUnits"] . "</td>";
        $temp .= "<td id='row'>$" .$u['Monthly'] . ".00</td>";
        $temp .= "</tr>";
    } 
}

答案 1 :(得分:0)

我尝试用json_decode对您的json进行解码,但不会。因为它返回语法错误。您可以使用json_last_error_msg()进行检查。我也从您的json字符串中删除了一些“”。您可以在jsonlint验证json字符串。现在它正在工作。

<?php

$jsonString = '{"Location" : {     
    "Units" : [
            {
                    "BonusComments": "THIS IS A BONUS DEAL",
                    "CubicFootage": 125,
                    "OrderGrouping": "0000001CONTAINER",
                    "SquareFootage": 25,
                    "TotalUnits": 45,
                    "UnitFeature": {
                        "Access": "",
                        "Climate": "NON-CLIMATE",
                        "Doors": "",
                        "Elevation": "OUTSIDE",
                        "Floor": "1",
                        "Product": "CONTAINER"
                        }
                }
                ]
  }}';

$jsonType = json_decode($jsonString);


foreach ($jsonType->Location->Units as $key => $value) {
    echo "KEY : ". $key."<br/>";
    echo $value->UnitFeature->Climate;
}
?>