PHP 将数组中的字符串分解为多维数组

PHP explode strings in array to multidimensional array

我看到过很多关于这个主题的问题,但没有一个接近我的情况。

我喜欢一个非常简单的文件夹路径作为键,想把这个数组做成一个多维数组。

我的当前数组

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

这是我尝试得到的结果:

[
  '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'
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ]
  ]
]

也许我可以用 array_walk_recursive somehow. I know explode 可以用来分割 / 的部分。

备注

$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