php - 在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
)
)
解决方案
由于我可能误解了并且您可能有很多,因此只需使用以下命令构建一个新数组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');
推荐阅读
- coldfusion - cfmail 中“from”属性的格式行为异常
- php - Laravel 全局变量仅在用户前缀中
- javascript - 静态文件无法加载nodejs
- python - 编码分类数据
- javascript - 使用javascript修改onclick链接
- python-3.x - 'ValueError: 在日/周/月/年转换日期时无法将浮点 NaN 转换为整数'
- laravel - 在 v-for 中的 v:bind 中使用动态名称
- javascript - 单击项目后关闭css悬停下拉菜单
- vue.js - 将“活动”类添加到 Nuxt.js Bootstrap
- excel - 初始化时清除用户表单