首页 > 解决方案 > 在php中搜索带有条件的数组

问题描述

我有一个 api,其中包含一个数组中的数组列表,并且该数组中的每个数组都有一个键 [attributes],并且在此键中,一个带有键 [CITY_NAME] 的数组

这是我的数组来自 api 这个数组编号是 0,但是每天这个数字都会改变,我的数字会出错,有什么好方法总是让我的城市数字使用键 [CITY_NAME]

我正在使用此代码获取数据

$json = file_get_contents($url);
$json_data = json_decode($json, true);
$data = $json_data['features'];
$mycity = $data[0]['attributes'];

Array
(
    [0] => Array
        (
            [attributes] => Array
                (
                    [CITY_NAME] => city1
                    [Name] => city1
                    [ADMIN_NAME] => city1
                    [POP_CLASS] => 5,000,000 to10,000,000
                    [Population] => 7676654
                    [Population_Data_Source] => Wikipedia
                    [Population_Data_Date] => 2018
                    [CityID] => 14
                    [Longitude] => 46.7614868685786
                    [Latitude] => 24.7388786516234
                    [Confirmed] => 0
                    [Recovered] => 0
                    [Deaths] => 0
                    [Active] => 0
                    [Tested] => 0
                    [Name_Eng] => city1
                    [Join_Count] => 61
                    [Confirmed_SUM] => 5152
                    [Deaths_SUM] => 9
                    [Recovered_SUM] => 1407
                    [Active_SUM] => 3736
                    [Tested_SUM] => 376607
                    [ObjectId] => 14
                )

        )
 [1] => Array
    (
        [attributes] => Array
            (
                [CITY_NAME] => city2
                [Name] => city2
                [ADMIN_NAME] => city2
                [POP_CLASS] => 1,000,000 to 5,000,000
                [Population] => 1675368
                [Population_Data_Source] => Wikipedia
                [Population_Data_Date] => 2010
                [CityID] => 9
                [Longitude] => 39.8148987363852
                [Latitude] => 21.4273876500039
                [Confirmed] => 0
                [Recovered] => 0
                [Deaths] => 0
                [Active] => 0
                [Tested] => 0
                [Name_Eng] => city2
                [Join_Count] => 59
                [Confirmed_SUM] => 6848
                [Deaths_SUM] => 85
                [Recovered_SUM] => 1145
                [Active_SUM] => 5618
                [Tested_SUM] => 0
                [ObjectId] => 9
            )

    )

标签: phparraysarraylistfetch-apiarray-key

解决方案


由于我可能误解了并且您可能有很多,因此只需使用以下命令构建一个新数组CITY_NAME

foreach($data as $values) {
    $result[$values['attributes']['CITY_NAME']] = $values['attributes'];
}

现在您可以通过以下方式访问CITY_NAME

echo $result['city1']['Population'];

这可能更容易。将所有数组中的所有内容提取attributes到一个数组中,然后根据索引创建一个数组CITY_NAME

$data = array_column(array_column($json_data['features'], 'attributes'), 
                     null, 'CITY_NAME');

推荐阅读