从文件路径字符串数组中创建多维值列表


PHP Create Multi-dimensional list of values from array of filepath strings

我有一个包含文件路径的数组

Array
(
    [0] => Array
        (
            [0] => cat/file1.php
        )
    [1] => Array
        (
            [0] => dog/file2.php
        )
    [2] => Array
        (
            [0] => cow/file3.php
        )
    [3] => Array
        (
            [0] => cow/file4.php
        )
    [4] => Array
        (
            [0] => dog/bowl/file5.php
        )
)

,并且需要将其转换为一个多维数组,该数组包含基于这些文件路径的文件名,即

Array
(
    [cat] => Array
        (
            [0] => file1.php
        )
    [dog] => Array
        (
            [0] => file2.php
            [bowl] => Array
                (
                     [0] => file5.php
                )
        )
    [cow] => Array
        (
            [0] => file3.php
            [1] => file4.php
        )
)

我一直在尝试展开字符串并使用for/foreach循环来构建一个非递归/递归的数组,但到目前为止还没有成功

是的,在遍历关联数组时可能会令人困惑,特别是在数组值中编码了文件夹结构的情况下。但没有恐惧和使用参考,一个人可以做到。下面是一个工作代码片段:

$array = [
    ['cat/file1.php'],
    ['dog/file2.php'],
    ['cow/file3.php'],
    ['cow/file4.php'],
    ['dog/bowl/file5.php'],
    ['dog/bowl/file6.php'],
    ['dog/bowl/soup/tomato/file7.php']
];
$result = [];
foreach ($array as $subArray)
{
    foreach ($subArray as $filePath)
    {
        $folders = explode('/', $filePath);
        $fileName = array_pop($folders); // The last part is always the filename
        $currentNode = &$result; // referencing by pointer
        foreach ($folders as $folder)
        {
            if (!isset($currentNode[$folder]))
                $currentNode[$folder] = [];
            $currentNode = &$currentNode[$folder]; // referencing by pointer
        }
        $currentNode[] = $fileName;
    }
}
var_dump($result);

结果如下:

array(3) {
  'cat' =>
  array(1) {
    [0] =>
    string(9) "file1.php"
  }
  'dog' =>
  array(2) {
    [0] =>
    string(9) "file2.php"
    'bowl' =>
    array(3) {
      [0] =>
      string(9) "file5.php"
      [1] =>
      string(9) "file6.php"
      'soup' =>
      array(1) {
        'tomato' =>
        array(1) {
          [0] =>
          string(9) "file7.php"
        }
      }
    }
  }
  'cow' =>
  array(2) {
    [0] =>
    string(9) "file3.php"
    [1] =>
    string(9) "file4.php"
  }
}

…我想这就是你想要的。