user1082428
user1082428

Reputation: 1081

PHP function to get recursive path keys with path

Given an array, I would like a flattened version of the array keys. Each array key would need the 'path' of the array, to that point, appended with an underscore.

An example explains this best.

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

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

the answer function would return this:

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

UPDATE:

Here is the work in progress. It will accept an array and return the array keys, but with no depth:

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;
}

Upvotes: 2

Views: 3961

Answers (2)

goat
goat

Reputation: 31854

$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);
}

Upvotes: 7

deceze
deceze

Reputation: 522636

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;
}

Demo here: http://codepad.viper-7.com/WQ3UYI

Upvotes: 2

Related Questions