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

时间:2016-09-28 11:13:59

标签: php arrays multidimensional-array filepath explode

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

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循环来非递归/递归地构建数组但到目前为止一直不成功

1 个答案:

答案 0 :(得分:2)

是的,在迭代关联数组时可能会造成混淆,尤其是在数组值编码的文件夹结构中。但是,没有恐惧和使用参考,人们可以管理。这是一个工作片段:

$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"
  }
}

......我想,这就是你想要的。