Reputation: 307
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.
Upvotes: 1
Views: 2069
Reputation: 18567
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)
Upvotes: 0
Reputation: 31749
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]
Upvotes: 1
Reputation: 3487
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?
Upvotes: 0