2016-09-28 57 views
0

我有一个包含文件路径PHP创建从文件路径字符串数组值的多维列表

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 
     ) 

) 

我一直在爆炸字符串,并使用/ foreach循环建立一个数组非递归/递归,但一直不成功尝试到目前为止

+1

可以提供您迄今为止尝试使用的代码,哪些不起作用? – rbr94

回答

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

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

+0

完美,谢谢!没有考虑使用参考 – user3495336