Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 616
user1082428 Avatar asked Apr 27 '26 19:04

user1082428


1 Answers

$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);
}
like image 165
goat Avatar answered Apr 29 '26 11:04

goat