PHP函数用路径获取递归路径密钥

时间:2011-12-05 22:11:28

标签: php arrays recursion

给定一个数组,我想要一个扁平版本的数组键。每个数组键都需要数组的“路径”,到那一点,附加一个下划线。

一个例子解释了这一点。

$arr = array("location"=>0,"details"=>array("width"=>0,"height"=>0,"level"=>array("three"=>0)));

function answer($arr) {....}

答案功能会返回:

array("location","details_width","details_height","details_level_three");

更新:

这是正在进行的工作。它将接受一个数组并返回数组键,但没有深度:

function recursive_keys($input)
{
    $output = array_keys($input);
    foreach($input as $sub){
        if(is_array($sub)){
            $output = array_merge($output, recursive_keys($sub));
        }
    }
    return $output;
}

2 个答案:

答案 0 :(得分:7)

$ritit = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr));
$results = array();
foreach ($ritit as $leafValue) {
    $path = array();
    foreach (range(0, $ritit->getDepth()) as $depth) {
        $path[] = $ritit->getSubIterator($depth)->key();
    }
    $results[] = join('_', $path);
}

答案 1 :(得分:2)

function recursive_keys(array $array, array $path = array()) {
    $result = array();
    foreach ($array as $key => $val) {
        $currentPath = array_merge($path, array($key));
        if (is_array($val)) {
            $result = array_merge($result, recursive_keys($val, $currentPath));
        } else {
            $result[] = join('_', $currentPath);
        }
    }
    return $result;
}

在这里演示:http://codepad.viper-7.com/WQ3UYI