gpt4 book ai didi

php - 查找值包含特定值的数组键

转载 作者:行者123 更新时间:2023-12-02 08:53:01 26 4
gpt4 key购买 nike

我有一个关联数组,其中每个值都是数字列表,如下所示:

$a['i']=[111, 333];

给定值333,我如何找到 key i。也就是说,包含 333 的列表的键。

最佳答案

如果主数组中的值是简单类型(数字、字符串等),您可能需要使用 array_search找到关联的 key 。在您的情况下,每个元素的值是另一个数组,因此您必须显式循环每个元素并在结果数组中搜索您的值。像这样的事情应该可以解决问题:

function get_key_from_value(array $arr, $needle)
{
foreach ($arr as $key => $value)
if (in_array($needle, $value, true))
return $key;
return null;
}

你可以这样调用它:

echo get_key_from_value($a, 333);

更新:评论中提到这不是通用解决方案,因此我实现了一个版本:

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;
}

可以这样调用(参数的顺序基于 array_search ):

echo array_search_recursive(333, $a);

关于php - 查找值包含特定值的数组键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41174060/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com