Joe
Joe

Reputation: 519

Build multidimensional array from keys

I can't seem to figure this out and I'm hoping someone has a magical recursive solution to this. I have a list of keys and basically I want to transform it into a nested array.

array('level1', 'level2', 'level3');

To

array(
    'level1' => array(
        'level2' => array(
             'level3' // last key in array should be just a value
        )
    )
)

Much appreciation to anyone who can help!

Upvotes: 1

Views: 60

Answers (2)

Jonathan Kuhn
Jonathan Kuhn

Reputation: 15311

You don't need recursion. A single loop is fine with references.

<?php
//array to iterate
$array = array('level1', 'level2', 'level3');

//contains our entire array
$out = array();

//temp variable to store references as we go down.
$tmp = &$out;

//get the last value off the array
$last = array_pop($array);

//loop over the array
foreach($array as $level){
    //make an array under the current level
    $tmp[$level] = array();
    //assign tmp to the new level
    $tmp = &$tmp[$level];
}
//assign the last key as the value under the last key
$tmp = $last;

//display output
print_r($out);

example: http://codepad.viper-7.com/zATfyo

And without references, working in reverse:

<?php
//array to iterate
$array = array('level1', 'level2', 'level3');

//get the last value off the array
$out = array_pop($array);

//flip the array backwards
$array = array_reverse($array);

//loop over the array
foreach($array as $level){
    $out = array($level=>$out);
}

//display output
print_r($out);

Example: http://codepad.viper-7.com/fgxeHO

Upvotes: 2

Vlad Preda
Vlad Preda

Reputation: 9930

Something like this should do the job:

function buildMultiDimensional(Array $arr)
{
    // the first value will become a new key
    $newKey = array_shift($arr);

    if (empty($arr)) {
        // this is where the recursion stops
        return $newKey;
    }

    // and the recursion !!!
    return array($newKey => buildMultiDimensional($arr));
}

$arr = array('level1', 'level2', 'level3', 'level4', 'level5');
var_dump(buildMultiDimensional($arr));

The result is what's expected:

array(1) {
    ["level1"]=>
  array(1) {
        ["level2"]=>
    array(1) {
            ["level3"]=>
      array(1) {
                ["level4"]=>
        string(6) "level5"
      }
    }
  }
}

Upvotes: 3

Related Questions