phparraysmultidimensional-arraykeypaths

Convert a flat array of key path strings to a multidimensional array terminating in empty arrays


If a single array of paths

$singleArray = array(
   '/Web',
   '/Web/Test1',
   '/Web/Test2', 
   '/Web/Test2/Subfolder',
   '/Web/Test3',
   '/Public'
);

From that array I want to create a mulitdimensional array, which keeps the keys, but creates subfolders in the correct parent folders. Later, I want to loop over the new array to create a folder tree (but that's not a problem).

The new array should look like this:

$multiArray = array(
   '/Web'=>array(
      '/Web/Test1'=>array(),
      '/Web/Test2'=>array(
          '/Web/Test2/Subfolder'=>array()
      ),
      '/Web/Test3'=>array()
   ),
   '/Public'=>array()
);

Solution

  • The code below will make the array you want. The key to solve your problem is to create a reference to the array every iteration.

    <?php
    $singleArray = array(
        '/Web',
        '/Web/Test1',
        '/Web/Test2',
        '/Web/Test2/Subfolder',
        '/Web/Test3',
        '/Public'
    );
    
    $multiArray = array();
    
    foreach ($singleArray as $path) {
        $parts       = explode('/', trim($path, '/'));
        $section     = &$multiArray;
        $sectionName = '';
    
        foreach ($parts as $part) {
            $sectionName .= '/' . $part;
    
            if (array_key_exists($sectionName, $section) === false) {
                $section[$sectionName] = array();
            }
    
            $section = &$section[$sectionName];
        }
    }