代码之家  ›  专栏  ›  技术社区  ›  user3495336

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

  •  0
  • user3495336  · 技术社区  · 8 年前

    我有一个包含文件路径的阵列阵列

    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 回复  |  直到 8 年前
        1
  •  2
  •   BVengerov    8 年前

    是的,在迭代关联数组时,尤其是在数组值中有文件夹结构编码的情况下,这可能会让人感到困惑。但是,没有恐惧和使用参考,一个人可以管理。下面是一个工作片段:

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

    …我想这正是你想要的。