I have an array of (many) arrays, encoded at different depths. The problem is that I know the key of the element I am searching for, but not the depth of the encoding. So for example it might beArray ( [1] => Array ( [1] => Array ('abcd' => 'a' ) )
or Array ('abcd' => 'a' )
So is there any way to find that abcd
key?
我有一个阵列(许多)阵列,编码在不同的深度。问题是,我知道我要搜索的元素的键,而不是编码的深度。例如,它可能是数组([1]=>数组([1]=>数组('abcd' => 'a'))或数组('abcd' => 'a'),那么有没有办法找到abcd键?
2 个解决方案
#1
0
function find_array_key($array,$keytofind){
$found=false;
if (is_array($array)&& $found==false){
foreach($array as $key=>$value){
if (is_array($value)&& $found==false){
find_array_key($array,$keytofind)
}else{
if ($found==false && $key=$keytofind){
$found=$value;
}
}
}
return $found;
}
I didn't run this code to test it but it should be pretty close to a nice recursive function for what you are trying to do and returning the value of the key you are looking for
我没有运行这个代码来测试它,但是它应该非常接近于一个很好的递归函数,因为你要做的是返回你要找的键值。
#2
0
if (array_key_exists('abcd', $search_array))
#1
0
function find_array_key($array,$keytofind){
$found=false;
if (is_array($array)&& $found==false){
foreach($array as $key=>$value){
if (is_array($value)&& $found==false){
find_array_key($array,$keytofind)
}else{
if ($found==false && $key=$keytofind){
$found=$value;
}
}
}
return $found;
}
I didn't run this code to test it but it should be pretty close to a nice recursive function for what you are trying to do and returning the value of the key you are looking for
我没有运行这个代码来测试它,但是它应该非常接近于一个很好的递归函数,因为你要做的是返回你要找的键值。
#2
0
if (array_key_exists('abcd', $search_array))