2 php
我有一个关联数组,其中每个值都是一个数字列表,如下所示:
$a['i']=[111, 333];
Run Code Online (Sandbox Code Playgroud)
鉴于价值333,我如何找到钥匙i.也就是说,包含列表的键333.
如果主数组中的值是简单类型 - 数字,字符串等 - 您可能希望array_search用于查找关联的键.在您的情况下,每个元素的值是另一个数组,因此您必须显式遍历每个元素并在结果数组中搜索您的值.像这样的东西应该做的伎俩:
function get_key_from_value(array $arr, $needle)
{
foreach ($arr as $key => $value)
if (in_array($needle, $value, true))
return $key;
return null;
}
Run Code Online (Sandbox Code Playgroud)
你会这样称呼它:
echo get_key_from_value($a, 333);
Run Code Online (Sandbox Code Playgroud)
更新:评论中提到这不是一个通用的解决方案,所以我实现了一个版本:
function array_search_recursive($needle, array $haystack, $strict = false)
{
foreach ($haystack as $key => $value) {
if (is_array($value)) {
if (!is_null(array_search_recursive($needle, $value, $strict))) {
return $key;
}
} else {
if ($strict && $value === $needle) {
return $key;
} else if (!$strict && $value == $needle) {
return $key;
}
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
可以像这样调用(参数的顺序基于array_search):
echo array_search_recursive(333, $a);
Run Code Online (Sandbox Code Playgroud)