Search code examples
phparraysmultidimensional-arrayhierarchical-datakeypaths

How to convert a flat array representing a keypath into a multidimensional array terminating at an empty array?


I have an array of keypaths like this:

 array('frank', 'john', 'dan')

and I need to build from that an

array(
    'frank' => array(
        'john' => array(
            'dan' => array()
        )
    )
)

It has to be dynamic because I won't always know how many keys are in the initial array

I tried some stuff but have to admit that I'm stumped.

The problem seems to be that I can't assign a variable number of dimensions to the array, where any time I assign array keys to the large array variable it has to be assigned to the root of the variable.

$keys = array('base', 'frank', 'john');
foreach ($keys as $k => $key) {
    if ($k > 0) {
        $largearray[$keys[$k-1]] = array($key => array());
    } elseif ($k>1) {
        $largearray = array_push($largearray[$keys[$k - 2]], array($keys[$k - 1] => array($key => array())));
    }
}

Solution

  • I hope this what you are looking for

        $arr = array('frank','john','dan');
    
        $finalArr = array();
        for ($x=count($arr) - 1; $x >= 0; $x--) {
            $arrElement = $arr[$x];
            $finalArr = array($arrElement => $finalArr);
        } 
    
        var_dump($finalArr);
    

    This will result to

    array (size=1)
      'frank' => 
        array (size=1)
          'john' => 
            array (size=1)
              'dan' => 
                array (size=0)
                  ...