我想过滤和对象数组以从中获取对象。例如,我有一个$data
数组,像这样
Array
(
[0] => stdClass Object
(
[Country] => ALA Aland Islands
[CountryCode] => AX
)
[1] => stdClass Object
(
[Country] => Afghanistan
[CountryCode] => AF
)
[2] => stdClass Object
(
[Country] => Albania
[CountryCode] => AL
)
[3] => stdClass Object
(
[Country] => Algeria
[CountryCode] => DZ
)
[4] => stdClass Object
(
[Country] => American Samoa
[CountryCode] => AS
)
)
我正在尝试过滤预期的对象,如:
$country_data = array_filter( $data, function($obj){
return 'AF' == $obj->CountryCode;
});
但是它不起作用。我正在尝试在包含该国家的最终结果中实现一个数组,像这样
Array(
[Country] => Albania
[CountryCode] => AL
)
答案 0 :(得分:0)
用json_decode()
用这种方式怎么样?
$array = json_decode(json_encode($country_data), true);
print_r($array);
完整的演示代码:
<?php
$array = array
(
'0' => array
(
'Country' => 'ALA Aland Islands',
'CountryCode' => 'AX'
)
,
'1' => array
(
'Country' => 'Afghanistan',
'CountryCode' => 'AF'
)
,
'2' =>array
(
'Country' => 'Albania',
'CountryCode' => 'AL'
)
,
'3' => array
(
'Country' => 'Algeria',
'CountryCode' => 'DZ'
)
,
'4' => array
(
'Country' => 'American Samoa',
'CountryCode' => 'AS'
)
);
$data = json_decode(json_encode($array));
$country_data = array_filter( $data, function($obj){
return 'AL' == $obj->CountryCode;
});
$array = json_decode(json_encode($country_data), true);
print_r($array);
?>