3 回答
TA贡献1812条经验 获得超5个赞
$data = json_decode($response, true)['data'];
print_r($this->continentFilter($data, 'AS'));
该函数将类似于:
private function continentFilter(array $data, string $continent): array
{
$filteredArray = [];
foreach ($data as $item) {
if ($item['continent'] === $continent) {
$filteredArray = $item;
break;
}
}
return $filteredArray;
}
TA贡献1811条经验 获得超6个赞
您可以使用json_decode数组标志和array_filter方法,如下所示:
$data = (json_decode($response, true))['data'];
$as = array_filter($data, function($item) {
return $item['continent'] === 'AS';
});
另请注意,上面示例中给出的 json 需要全部用大括号括起来,如下所示:
{
"data": {
...
}
TA贡献1802条经验 获得超5个赞
如果大陆值与“AS”匹配,您可以循环遍历每个对象并推送到新数组。
使用$key => $value允许您保留索引。
例子:
$filtered = [];
foreach ( $data->data as $key => $value )
{
if ( $value->continent === "AS" )
{
$filtered[$key] = $value;
}
}
print_r($filtered);
会给你:
[AE] => stdClass Object
(
[iso_alpha2] => AE
[name] => United Arab Emirates
[continent] => AS
[advisory] => stdClass Object
(
[score] => 3.1
[sources_active] => 7
[message] =>
[updated] => 2020-08-04 07:21:19
[source] => https://www.travel-advisory.info/united-arab-emirates
)
)
[AF] => stdClass Object
(
[iso_alpha2] => AF
[name] => Afghanistan
[continent] => AS
[advisory] => stdClass Object
(
[score] => 5
[sources_active] => 10
[message] =>
[updated] => 2020-08-04 07:21:19
[source] => https://www.travel-advisory.info/afghanistan
)
)
...
- 3 回答
- 0 关注
- 89 浏览
添加回答
举报