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

时间:2018-01-31 11:37:41

标签: php arrays recursion multidimensional-array explode

我已经看到很多关于这个主题的问题,但是我的情况并非如此。

我喜欢一个非常简单的文件夹路径作为键,并希望将数组转换为多维数组。

我当前的数组

[
  '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。我知道explode可用于按/分割部分。

备注

  • projects/project-a没有孩子。
  • about除了最后一个孩子之外的所有孩子都没有路径。
  • 阵列的深度未知。

1 个答案:

答案 0 :(得分:2)

$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