【问题标题】:PHP search for Key in multidimensional arrayPHP在多维数组中搜索Key
【发布时间】:2011-05-22 07:09:00
【问题描述】:
我有这个:
Array
(
[carx] => Array
(
[no] => 63
)
[cary] => Array
(
[no] => 64
)
)
当我有 no=63 时,如何找到钥匙 carx ?我知道如何使用array_search(),但这个有点棘手。就像我可以找到键名 id 而我有 63 但这个有点棘手。
有人可以帮我吗?
【问题讨论】:
标签:
php
arrays
search
multidimensional-array
【解决方案1】:
foreach ($array as $i => $v) $array[$i] = $v['no'];
$key = array_search(63, $array);
【解决方案2】:
所以你不是第一级的 id 键,所以循环遍历,当你找到匹配时停止循环并跳出 foreach
$id = 0;
$needle = 63;
foreach($array as $i => $v)
{
if ($v['no'] == $needle)
{
$id = $i;
break 1;
}
}
// do what like with any other nested parts now
print_r($array[$id]);
然后您可以使用该键获取整个嵌套数组。
【解决方案3】:
这有用吗?我用它对数组和对象进行通用搜索。注意:它没有经过速度/压力测试。欢迎指出任何明显的问题。
function arrayKeySearch(array $haystack, string $search_key, &$output_value, int $occurence = 1){
$result = false;
$search_occurences = 0;
$output_value = null;
if($occurence < 1){ $occurence = 1; }
foreach($haystack as $key => $value){
if($key == $search_key){
$search_occurences++;
if($search_occurences == $occurence){
$result = true;
$output_value = $value;
break;
}
}else if(is_array($value) || is_object($value)){
if(is_object($value)){
$value = (array)$value;
}
$result = arrayKeySearch($value, $search_key, $output_value, $occurence);
if($result){
break;
}
}
}
return $result;
}