在条件为 php 的数组中搜索

search inside arrays with condition in php

我有一个 api,其中一个数组内有一个数组列表,该数组内的每个数组都有一个键 [属性],并且在该键内有一个数组,键为 [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
            )

    )

可能是我理解错了,你可能理解错了很多,建个新数组就可以了 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');