PHP 7 - How to search for multiple specific members of an array

时间:2018-03-25 19:56:03

标签: php arrays

I have a PHP array that looks like this:

array (size=3)
  'CA,Santa Barbara' => 
    array (size=2)
      'state' => string 'CA' (length=2)
      'city' => string 'Santa Barbara' (length=13)
  'KS,Andover' => 
    array (size=2)
      'state' => string 'KS' (length=2)
      'city' => string 'Andover' (length=7)
  'KS,Wichita' => 
    array (size=2)
      'state' => string 'KS' (length=2)
      'city' => string 'Wichita' (length=7)

I need to return all the array members who have the values:

state => 'KS'

I am needing to get an array back that looks like this:

array (size=2)
  'KS,Andover' => 
    array (size=2)
      'state' => string 'KS' (length=2)
      'city' => string 'Andover' (length=7)
  'KS,Wichita' => 
    array (size=2)
      'state' => string 'KS' (length=2)
      'city' => string 'Wichita' (length=7)

Is there a PHP array function that does this? I have found array_search() but that only returns the first match. I need ALL matches.

1 个答案:

答案 0 :(得分:9)

You could use array_filter() to remove all unneeded values:

$array = array (
    'CA,Santa Barbara' => array (
        'state' =>  'CA' ,
        'city' =>  'Santa Barbara' ,
    ),
    'KS,Andover' => array (
        'state' =>  'KS' ,
        'city' =>  'Andover' ,
    ),
    'KS,Wichita' => array (
        'state' =>  'KS' ,
        'city' =>  'Wichita' ,
    ),
);
// keep all values with state is "KS":
$out = array_filter($array, function($v) {
    return $v['state'] == 'KS';
});

print_r($out);

Outputs:

Array(
    [KS,Andover] => Array(
            [state] => KS
            [city] => Andover
        )
    [KS,Wichita] => Array(
            [state] => KS
            [city] => Wichita
        )
)

To use another variable inside the anonymous function, you can pass it using use() :

$state = 'KS';
$out = array_filter($array, function($v) use ($state) {
    return $v['state'] == $state;
});