如何在PHP中访问JSON文件中的特定对象?

时间:2019-11-09 12:20:46

标签: php arrays json loops

我将以下内容作为JSON数组的一部分

"appendix": {
  "airlines": [
   {
    "fs": "AA",
    "iata": "AA",
    "icao": "AAL",
    "name": "American Airlines",
    "phoneNumber": "08457-567-567",
    "active": true
   },
   {
    "fs": "LY",
    "iata": "LY",
    "icao": "ELY",
    "name": "El Al",
    "phoneNumber": "+ 972-3-9771111",
    "active": true
   }

我想获得字符串中唯一具有“ iata”为“ AA”(即“美国航空”)的“名称”。我尝试在其中编写for循环

$iata = "AA"
$appendix_airlines = $array["airlines"][0];

$app_airlines_length = count($appendix_airlines);      

        for ($i = 0; $i <= $app_airlines_length; $i ++) {
                if ($appendix_airlines[$i]["iata"] == "AA") {
                    echo $appendix_airlines[$i]["name"];
                };
        }

但是,这只会返回未定义的偏移= 0,未定义的偏移= 1等错误。我该如何解决?

基本上,我希望它根据输入的IATA代码获得航空公司的名称。

3 个答案:

答案 0 :(得分:0)

这是带有json_decode的脚本,

$temp = json_decode($json,true); // true as 2nd for raw array
$iata = "AA";
foreach ($temp['appendix']['airlines'] as $key => $value) {
    if($value['iata'] == $iata){
         echo $value["name"]."<br>";
    }
}

Demo

输出

American Airlines

答案 1 :(得分:0)

您尚未选择数组,而是选择了数组的第一个对象:

$appendix_airlines = $array["airlines"][0];

只需更改为:

$appendix_airlines = $array["airlines"];

$app_airlines_length = count($appendix_airlines);      

        for ($i = 0; $i < $app_airlines_length; $i ++) {
                if ($appendix_airlines[$i]["iata"] == "AA") {
                    echo $appendix_airlines[$i]["name"];
                };
        }

注意ArrayIndexOutOfBondsException

for ($i = 0; $i <= $app_airlines_length; $i ++)

代码应为$i < $app_airlines_length

答案 2 :(得分:0)

array_column非常适合在Php中处理JSON:

<?php

$json =<<< 'JSON'
{
    "appendix": {
        "airlines": [
            {
                "fs": "AA",
                "iata": "AA",
                "icao": "AAL",
                "name": "American Airlines",
                "phoneNumber": "08457-567-567",
                "active": true
            },
            {
                "fs": "LY",
                "iata": "LY",
                "icao": "ELY",
                "name": "El Al",
                "phoneNumber": "+ 972-3-9771111",
                "active": true
            }
        ]
    }
}
JSON;
$data       = json_decode($json, true);
$iata_names = array_column(
    $data['appendix']['airlines'], 
    'name', 
    'iata'
);

echo $iata_names['AA'] ?? 'N/A';

输出:

American Airlines

array_column的结果如下:

var_export($iata_names);

输出:

array (
    'AA' => 'American Airlines',
    'LY' => 'El Al',
  )