简体   繁体   中英

Check for key-value pair in multidimensional array

I have the follow array:

Array
(
    [0] => Array
        (
            [type] => foo
        )

    [1] => Array
        (
            [type] => bar
        )

    [2] => Array
        (
            [type] => bar
        )
)

and need to know if exists one or more type which value is bar , without do this:

foreach ($arrayOfTypes as $type) {
    if ($type['type'] == 'bar')
    {
        // Stuff here
    }
}

(Only for learning purposes)

I'd go with array_filter() ;

$filteredArray = array_filter($stuff, function($item){

    return $item['type'] == 'bar';

});

if( count($filteredArray) > 0 ){

    echo 'There was a bar item in array.';

}else{

    echo 'No luck sorry!';

}

Use in_array: http://se.php.net/manual/en/function.in-array.php

Combine it with array_map to flatten what you have. Like so:

$new_array = array_map( function( $arr ) {
    return $arr['type'];
}, $array );
in_array( 'bar', $new_array );

Honestly a foreach loop or moonwave99's array-filter answer is probably going to be your best bet, but if what you're looking is the shortest code possible and creativity that will make most programmers gag, you could try serialize -ing the array and using string-searching functions:

serialize(array(
        0=>array(
            'type'  => 'foo'
        ),
        1=>array(
            'type'  => 'bar'
        ),
        2=>array(
            'type'  => 'bar'
        )
    ))

becomes

a:3:{i:0;a:1:{s:4:"type";s:3:"foo";}i:1;a:1:{s:4:"type";s:3:"bar";}i:2;a:1:{s:4:"type";s:3:"bar";}}

So you can now run a strpos() or preg_match() function to find them. So your whole function would look like :

$exists = strpos('{s:4:"type";s:3:"bar";}',serialize($arrayOfTypes)); //returns number or false

It's short, it's snappy, and get's the job done for simple string keypairs.

This is basically the same as moonwave99's solution but slightly more useful as it's in a function that you can feed a key/value pair to as well, so it can be used to search for any key/value combo:

function isKVInArray($k, $v, $array) {
    $filtered = array_filter($array, function($item) use($k,$v) {
        return $item[$k] == $v;
    });
    if(count($filtered)>=1) return true;
    else return false;
}

$k = 'live';
$v = 'y';
$my_array = array(
    0=>array(
        'live'=>'n',
        'something_else'=>'a'
    ),
    1=>array(
        'live'=>'y',
        'something_else'=>'b'
    ),
    2=>array(
        'live'=>'n',
        'something_else'=>'c'
    )
);


if(isKVInArray($k, $v, $my_array)) echo "$k=>$v was found in the array.";
else echo 'No luck sorry!';

there's another simple way which is useful when you need to count all the different values

foreach ($arrayOfTypes as $type) $cnt[$type['type']]++;

To get the number of 'bar' (or to get the count of another value):

echo($cnt['bar']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM