phparraysrecursionmultidimensional-arrayexplode

Parse a flat, associative array with keys representing a delimited key path into a multidimensional, associative array


I've seen many questions around this topic, but not any near the case I have.

I have like a really simple folder path as key and want to make the array into a multidimensional array.

My current array

[
  'projects'                  => 'A path',
  'projects/project-a'        => 'Another path',
  'projects/project-b'        => 'Yet another path',
  'about/me/and/someone/else' => 'Path about me'
]

This is the result I try to get:

[
  'projects' => [
    'path'     => 'A path',
    'children' => [
      'project-a' => [
        'path' => 'Another path'
      ],
      'project-b' => [
        'path' => 'Yet another path'
      ]
    ]
  ],
  'about' => [
    'children' => [
      'me' => [
        'children' => [
          'and' => [
            'children' => [
              'someone' => [
                'children' => [
                  'else' => [
                    'path' => 'Path about me'
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]

Maybe I can use array_walk_recursive somehow. I know explode can be used to split the parts by /.

Notes


Solution

  • $result = [];
    
    foreach($arr as $k=>$v) {
      $path = explode('/', $k);
      // temporary array for one path
      $temp = [];
      // Pointer, used to add a next level 
      $p = &$temp;
      // Save the last part of path
      $last = array_pop($path);
      foreach($path as $s) {
        // Make level upto the last
        $p[$s] = ['children' => []];
        $p = &$p[$s]['children'];
      }
     // Add a value 
     $p[$last] = ['path' => $v];
     $result = array_merge_recursive($result, $temp);
    }
    print_r($result);
    

    demo