如何在一定深度搜索数组


How to search array at certain depth?

我有一个具有许多深度的多维数组,因为我有大约 9 维,所以我将展示我如何访问它们的代码

示例代码:

$attribute[5]['group'][1]['f'][4]['id'][18]['fc'][20]

样本数组

有没有办法根据我想要的深度和键来获取数组,而不知道之前的级别

假设我只有键 20(最后一个键)等部分信息,有没有办法用键 9 获取第 20 维的数组

理想函数应如下所示

function get_by_depth($m_array,$depth,$key){
}
$array=get_by_depth($attribute,9,20);
//will search through available level 9 item
//if there are key 20 at level 9 return the array or value 

这样的东西可以使用您的示例数组数据。

function get_by_depth($array, $depth, $key, $currentDepth = 0)
{
    if ($currentDepth == $depth) {
        return isset($array[$key]) ? $array[$key] : null;
    } else {
        foreach ($array as $k => $v) {
            if (is_array($v)) {
                return get_by_depth($v, $depth, $key, ++$currentDepth);
            }
        }
    }
}

echo "<pre>";
print_r(get_by_depth($array,8,'image'));exit;

注意这假设每个数组内部最多只包含一个数组。如果您需要一个可以处理包含相同深度级别的多个数组的数组的解决方案,那么将有更多的工作要做

一种方法是使用递归

function recursive($array, $searchKey){
    foreach($array as $key => $value){
        //If $value is an array.
        If($searchKey == $key){
           echo $value; //or do something now that it is found
           break;
        }
        if(is_array($value)){
            //We need to loop through it.
            recursive($value, $searchKey);
        } 
    }
}
function depth(&$array, $depth_level = 0) {
    $cdepth = 0;
    while($a = array_shift($array)) { $cdepth++;
        if($depth_level==$cdepth) return $a;
    }
    return $array;
}