简体   繁体   中英

PHP: Return value associated with specific key in an array of associative arrays

In PHP 5.5+, how do I check if the given array of associative arrays contains specific key/value pairs. For example:

$some_array = array(
            array(
                "value"=> 1,
                "k1"=> "austin",
                "k2"=> "texas",
                "k3"=> "us"
            ),
            array(
                "value"=> 15,
                "k1"=> "bali",
                "k2"=> "ubud",
                "k3"=> "indonesia"
            ),
            array(
                "value"=> 26,
                "k1"=> "hyd",
                "k2"=> "telangana",
                "k3"=> "india"
            )
));

How do I return the value associated with k1='bali', k2='ubud' and k3='indonesia'? I can loop through each element to check if that combination exists in the array but is there a simpler way to handle this?

If you have an target array of keys and values, you can filter the main array to only include child arrays that match all the key/value combinations in your target array using array_diff_assoc .

$target =array(
    "k1"=> "bali",
    "k2"=> "ubud",
    "k3"=> "indonesia"
);

$matches = array_filter($some_array, function($item) use ($target) {
    return !array_diff_assoc($target, $item);
});

Inside the array_filter callback, array_diff_assoc will return all the key/value pairs in $target that are not present in $item , so if they all match, you'll get an empty array. Negating that result with ! will return true for matching arrays and false for non-matching arrays.

$matches will be an array of all the child arrays matching your set of key/value pairs, or an empty array if none match.

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