2014-07-15 102 views
1

內爆的多維數組我想加入數組鍵與在端作爲文件本身的值的文件路徑(下面所述陣列是「文件樹」)通過鍵和值用PHP

陣列(深度,大小和鍵名是動態的):

[0] => bla.tif 
[1] => quux.tif 
[foo] => Array (
     [bar] => Array (
       [lorem] => Array (
         [1] => ipsum.tif 
         [2] => doler.tif 
       ) 
     ) 
) 
[bar] => Array (
     [qux] => Array (
       [baz] => Array (
         [1] => ipsum.tif 
         [2] => ufo.tif 
       ) 
     ) 
) 

這個結果就可以了:

[0] => bla.tif 
[1] => quux.tif 
[2] => foo/bar/lorem/ipsum.tif 
[3] => foo/bar/lorem/doler.tif 
[4] => bar/qux/baz/ipsum.tif 
[5] => bar/qux/baz/ufo.tif 

也許有也是一個純PHP解決方案。我用array_map嘗試過,但結果不夠好。

+0

與嘗試:recursiveiterator。 http://php.net/manual/en/class.recursivearrayiterator.php – Wikunia

+0

有了這個結構,你將如何處理目錄名稱實際上是數字的情況? – Yoshi

+0

@Yoshi,那種情況不會發生 - 所有的目錄名都已經用字母命名。 (這個不會改變。) – CodeBrauer

回答

2

我會使用遞歸函數來摺疊這個數組。這裏有一個例子:

function collapse($path, $collapse, &$result) 
{ 
    foreach($collapse AS $key => $value) 
    { 
    if(is_array($value)) 
    { 
     collapse($path . $key . "/", $value, $result); 
     continue; 
    } 
    $result[] = $path . $value; 
    } 
} 

這裏是如何使用:

$result = array(); 
$toCollapse = /* The multidimentional array */; 
collapse("", $toCollapse, $result); 

$result將包含 「崩盤」 陣列

+0

謝謝!這正是我尋找的。 – CodeBrauer