php数组过滤器从数组对象中过滤对象

时间:2020-04-12 14:52:04

标签: php filter

我想过滤和对象数组以从中获取对象。例如,我有一个$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
)

1 个答案:

答案 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);
?>

演示: https://3v4l.org/WUlCC