简体   繁体   中英

PHP array_filter in multidimensional associative array

I need to find the value for a key by searching for another value within the same array of a multidimensional array.

This is the given array:

<?php 

$users = array(

    "userA" => array(
                "email" => "userA@email.com",
                "language" => "en",
            ),

    "userB" => array(
                "email" => "userB@email.com",
                "language" => "de",
            ),

    "userC" => array(
                "email" => "userC@email.com",
                "language" => "it",
            ),

);

?>

Example: I want to input...

$lang = 'de';

...and get the value for "email" of that same item. So in this case it should output:

userB@email.com

The languages are unique, so there will only be one possible match.

If this already might be asked, I apologize, but I couldn't find anything with that structure and this search condition.

Thanks in advance.

You can use array_column() for this -

// Generate array with language as key
$new = array_column($users, 'email', 'language');
// access array value (email) by language
echo $new['de'];

Output

userB@email.com

This might be difficult to achieve with array_filter , but you could look at other alternatives, like a foreach loop and array_push

$filtered = [];

foreach($users as $key => $value) {
    if($value['language'] == 'de') {
        array_push($filtered, [$key => $value]);
    }
}

See array_filter with assoc array?

There is one recursive way to achieve this,

function recursive_array_search($needle,$haystack) {
    foreach($haystack as $key=>$value) {
        $current_key=$key;
        if($needle===$value OR (is_array($value) && recursive_array_search($needle,$value) !== false)) {
            return $current_key;
        }
    }
    return false;
}
// searching 'de' and getting all array or specific value by key. Its multipurpose method.
$temp = $users[recursive_array_search('de', $users)]['email']; 
print_r($temp);

Ref Link .

( Demo )

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