PHP-如果键存在于多维关联数组中,则返回其位置
我有一个多维关联数组。顶级键是数字,其中的关联数组具有键和值的字符串 以下是阵列转储的示例:PHP-如果键存在于多维关联数组中,则返回其位置,php,arrays,multidimensional-array,Php,Arrays,Multidimensional Array,我有一个多维关联数组。顶级键是数字,其中的关联数组具有键和值的字符串 以下是阵列转储的示例: Array ( [1] => Array ( [AC21T12-M01] => 54318 ) [2] => Array ( [AC03T11-F01] => 54480 ) ) 所以我想搜索'AC03T11-F01'并返回2作为键位置 我尝试了a
Array
(
[1] => Array
(
[AC21T12-M01] => 54318
)
[2] => Array
(
[AC03T11-F01] => 54480
)
)
所以我想搜索'AC03T11-F01'并返回2作为键位置
我尝试了array\u搜索('AC03T11-F01',$array)代码>但它没有返回任何内容,所以我猜这并不像我想的那样简单
我在搜索某个值时使用了下面的函数来设置关键点位置,因此,是否也可以对其进行调整以搜索关键点
function getParentStack($child, $stack) {
foreach ($stack as $k => $v) {
if (is_array($v)) {
// If the current element of the array is an array, recurse it and capture the return
$return = getParentStack($child, $v);
// If the return is an array, stack it and return it
if (is_array($return)) {
//return array($k => $return);
return $k;
}
} else {
// Since we are not on an array, compare directly
if ($v == $child) {
// And if we match, stack it and return it
return array($k => $child);
}
}
}
// Return false since there was nothing found
return false;
}
现在检查$found
您可以筛选阵列,然后请求密钥:
$filtered = array_filter($array, function(item) {
return item === 'AC03T11-F01'
});
var_dump( array_keys( $filtered ) );
//⇒ [ 2 ]
是否要检索第一次出现的密钥:
$keys = array_keys( array_filter($array, function(item) {
return item === 'AC03T11-F01'
}));
echo ($key = count( $keys ) > 0 ? $keys[0] : null);
//⇒ 2
这不会将单个键作为操作返回requested@Kleskowy更新了答案。谢谢@mudasobwa。我接受了Abracadver的回答,但我也很感激你的回答:)谢谢@Abracadver。这非常有效,而且只有几行。完美:)
$keys = array_keys( array_filter($array, function(item) {
return item === 'AC03T11-F01'
}));
echo ($key = count( $keys ) > 0 ? $keys[0] : null);
//⇒ 2