繁体   English   中英

PHP -> Json,访问嵌套数组

[英]PHP -> Json, access to nested Arrays

我正在尝试使用 PHP 访问来自 json 的嵌套信息。 到目前为止我得到了什么:以下 Json

 { "Response": { "MetaInfo": { "Timestamp": "2021-02-05T16:59:45.379+0000" }, "View": [ { "_type": "SearchResultsViewType", "ViewId": 0, "Result": [ { "Relevance": 1, "MatchLevel": "city", "MatchQuality": { "City": 1 }, "Location": { "LocationId": "NT_ZJPKK1T.yfVXpHzv5zfPOC", "LocationType": "point", "DisplayPosition": { "Latitude": 48.13642, "Longitude": 11.57755 }, "NavigationPosition": [ { "Latitude": 48.13642, "Longitude": 11.57755 } ], "MapView": { "TopLeft": { "Latitude": 48.24824, "Longitude": 11.36084 }, "BottomRight": { "Latitude": 48.06175, "Longitude": 11.72291 } }, "Address": { "Label": "München, Bayern, Deutschland", "Country": "DEU", "State": "Bayern", "County": "München (Stadt)", "City": "München", "PostalCode": "80331", "AdditionalData": [ { "value": "Deutschland", "key": "CountryName" }, { "value": "Bayern", "key": "StateName" }, { "value": "München (Stadt)", "key": "CountyName" } ] } } } ] } ] } }

尝试访问“NavigationPosition”-> 纬度和经度。 所以我使用 json_decode 来访问外部 API。 我尝试使用 foreach 循环访问嵌套数组元素,但到目前为止没有成功,所以我决定向您寻求帮助。 我只得到有关 MetaInfo 的信息,它是一个数组,但仅此而已……谢谢,我不明白,需要提示。

 foreach($json_data as $elem) { echo($elem['MetaInfo']); echo("<br/>"); }

当打印出 print_r($elem['View'] 我得到以下 PHP:

 [0] => Array ( [_type] => SearchResultsViewType [ViewId] => 0 [Result] => Array ( [0] => Array ( [Relevance] => 1 [MatchLevel] => city [MatchQuality] => Array ( [City] => 1 ) [Location] => Array ( [LocationId] => NT_okXlwMMLN7VL.8UaGPioOC [LocationType] => point [DisplayPosition] => Array ( [Latitude] => 48.17105 [Longitude] => 11.81632 ) [NavigationPosition] => Array ( [0] => Array ( [Latitude] => 48.17105 [Longitude] => 11.81632 ) ) [MapView] => Array ( [TopLeft] => Array ( [Latitude] => 48.18599 [Longitude] => 11.76932 ) [BottomRight] => Array ( [Latitude] => 48.1497 [Longitude] => 11.83995 ) ) [Address] => Array ( [Label] => Poing, Bayern, Deutschland [Country] => DEU [State] => Bayern [County] => Ebersberg [City] => Poing [PostalCode] => 85586 [AdditionalData] => Array ( [0] => Array ( [value] => Deutschland [key] => CountryName ) [1] => Array ( [value] => Bayern [key] => StateName ) [2] => Array ( [value] => Ebersberg [key] => CountyName ) ) ) ) ) ) )

谢谢你。 亚当

从嵌套结构访问数据有一个一站式解决方案:

<?php

function getFromNested($source, array $path)
{
    $result = null;
    getFromNestedRecursive($source, array_reverse($path), $result);
    return $result;
}

function isArrayAssoc(array $input): bool
{
    if([] === $input) {
        return false;
    }
    return array_keys($input) !== range(0, count($input) - 1);
}


function getFromNestedRecursive($source, array $pathStack, &$result): void
{
    // let's iterate every path part from stack
    while(count($pathStack)) {
        if(is_array($source) && !isArrayAssoc($source)) {
            // the result will be multiple
            if(!is_array($result)) {
                $result = [];
            }
            // and we need to use recursive call for each item of this array
            foreach($source as $item) {
                getFromNestedRecursive($item, $pathStack, $result);
            }
            // we don't need to do something in this recursive branch
            return;
        }

        $key = array_pop($pathStack);

        if(is_array($source)) {
            if(!array_key_exists($key, $source)) {
                // path part key is missing in source array
                // we cannot go deeper
                return;
            }
            // go to the next nested level
            $source = $source[$key];
        } elseif(is_object($source)) {
            $getterName = 'get'.ucfirst($key);
            if(method_exists($source, $getterName)) {
                // go to the next nested level
                $source = $source->{$getterName}();
            } elseif(property_exists($source, $key)) {
                // go to the next nested level
                $source = $source->{$key};
            } else {
                // path part key is missing in source object
                // we cannot go deeper
                return;
            }
        } else {
            // source is scalar, so we can't go to the next depth level
            // we cannot go deeper
            return;
        }

        // when it's not the last iteration of the stack
        // and the source is non-associative array (list)
        if(count($pathStack) && is_array($source) && !isArrayAssoc($source)) {
            // the result will be multiple
            if(!is_array($result)) {
                $result = [];
            }
            // and we need to use recursive call for each item of this array
            foreach($source as $item) {
                getFromNestedRecursive($item, $pathStack, $result);
            }
            // we don't need to do something in this recursive branch
            return;
        }
    }

    // now path stack is empty — we reached target value of given path in source argument
    // so if result is multiple
    if(is_array($result)) {
        // we append source to result
        $result[] = $source;
    } else {
        // result is single
        $result = $source;
    }
    // that's all folks!
}

$data = json_decode('{
  "Response": {
    "MetaInfo": {
      "Timestamp": "2021-02-05T16:59:45.379+0000"
    },
    "View": [
      {
        "_type": "SearchResultsViewType",
        "ViewId": 0,
        "Result": [
          {
            "Relevance": 1,
            "MatchLevel": "city",
            "MatchQuality": {
              "City": 1
            },
            "Location": {
              "LocationId": "NT_ZJPKK1T.yfVXpHzv5zfPOC",
              "LocationType": "point",
              "DisplayPosition": {
                "Latitude": 48.13642,
                "Longitude": 11.57755
              },
              "NavigationPosition": [
                {
                  "Latitude": 48.13642,
                  "Longitude": 11.57755
                }
              ],
              "MapView": {
                "TopLeft": {
                  "Latitude": 48.24824,
                  "Longitude": 11.36084
                },
                "BottomRight": {
                  "Latitude": 48.06175,
                  "Longitude": 11.72291
                }
              },
              "Address": {
                "Label": "München, Bayern, Deutschland",
                "Country": "DEU",
                "State": "Bayern",
                "County": "München (Stadt)",
                "City": "München",
                "PostalCode": "80331",
                "AdditionalData": [
                  {
                    "value": "Deutschland",
                    "key": "CountryName"
                  },
                  {
                    "value": "Bayern",
                    "key": "StateName"
                  },
                  {
                    "value": "München (Stadt)",
                    "key": "CountyName"
                  }
                ]
              }
            }
          }
        ]
      }
    ]
  }
}', true);

$timestamp = getFromNested($data, ['Response', 'MetaInfo', 'Timestamp']);
var_dump($timestamp); // 2021-02-05T16:59:45.379+0000

$addressesLabels = getFromNested($data, ['Response', 'View', 'Result', 'Location', 'Address', 'Label']);
var_dump($addressesLabels); // ["München, Bayern, Deutschland"]

您也可以从我的包中使用它: https ://github.com/Smoren/nested-accessor-php

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM