[英]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. 例如:如果给定“ tiger”,我想检索“ feline”键。
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: 您需要2个循环,外部循环遍历键,内部循环在每个键中找到匹配的值,如下所示:
<?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;
}
}
}
?> ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.