I have an api with a list of arrays inside one array and each array inside this array it has one key [attributes] and inside this key one array with key [CITY_NAME]
this is my array coming from api this array number is 0 but every day this number is changed and my figures come wrong, what is the good way to always have my city figures using the key [CITY_NAME]
I am fetching the data using this code
$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 ) )
Advertisement
Answer
Since I may have misunderstood and you may have many, just build a new array with CITY_NAME
:
foreach($data as $values) { $result[$values['attributes']['CITY_NAME']] = $values['attributes']; }
Now you can access by CITY_NAME
:
echo $result['city1']['Population'];
This might be easier. Extract all attributes
from all arrays into an array, then create an array from that indexed by CITY_NAME
:
$data = array_column(array_column($json_data['features'], 'attributes'), null, 'CITY_NAME');