1

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" => "[email protected]",
                "language" => "en",
            ),

    "userB" => array(
                "email" => "[email protected]",
                "language" => "de",
            ),

    "userC" => array(
                "email" => "[email protected]",
                "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:

[email protected]

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.

3 Answers 3

1

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

[email protected]
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.