简体   繁体   中英

Given an associative array where the values are flat arrays, how can I search the values and return the key?

Given the following associative array:

$array = [
    'canine' => ['dog', 'wolf'],
    'feline' => ['cat', 'tiger', 'jaguar']
];

What existing function (if any) would be valuable to use to retrieve the 'canine' or 'feline' key?

For example: if given 'tiger' I want to retrieve the 'feline' key.

I am late, ther are some other answers, all are good

But here is mine one:

function flatArraySearch($arr, $val) {
    foreach($arr as $key=>$subArr) {
        if (array_search($val,$subArr) !== false) {
            return $key;
        } 
    }
    return false;
}

$array = [
    'canine' => ['dog', 'wolf'],
    'feline' => ['cat', 'tiger', 'jaguar']
];

echo flatArraySearch($array, 'tiger')."\n";

echo flatArraySearch($array, 'wolf')."\n";

echo flatArraySearch($array, 'bird')."\n";

I believe there is no built-in function for it, but you can easily write it on your own.

function search($search, $array) {
   foreach($array as $key => $value)
      if (in_array($search, $value)) return $key;
   return FALSE;
}

You need 2 loops, the outer loop goes through the key, the inner loop find the matched value in each key, like this:

<?php
$array = [
'canine' => ['dog', 'wolf'],
'feline' => ['cat', 'tiger', 'jaguar']
];

$find = 'tiger';

foreach ($array as $key => $valueArray) {
    foreach ($valueArray as $value) {
        if ($value == $find) {
            echo $key;
            break;
        }
    }
}

?>

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