次のような配列がある場合:
array(
'c' => array(
'Folder1' => array(
'Flower.jpg',
'Monkey.jpg',
...
),
'Folder2' => array(
'Binkie.txt',
...
),
),
),
再帰関数を使用できます:
<?php
$arr = array(
'c' => array(
'Folder1' => array(
'Flower.jpg',
'Monkey.jpg',
//...
),
'Folder2' => array(
'Binkie.txt',
//...
),
),
);
function drawTree($container, $nesting = 0)
{
foreach ($container as $folder => $sub) {
if (is_array($sub)) {
echo str_repeat('.', $nesting) . $folder . '<br>';
drawTree($sub, $nesting + 1);
} else {
echo str_repeat('.', $nesting) . $sub . '<br>';
}
}
}
drawTree($arr);
パスを配列ツリーに変換するには、これを使用します。
$arr = array(
'C/Folder1/Flower.jpg',
'C/Folder1/Monkey.jpg',
'C/Folder1/Hello.jpg',
'C/Folder2/Binkie.txt',
'C/Folder2/Spike.png',
'C/Folder3/Django.jpg',
'C/Folder3/Tessje.tiff',
);
$result = array();
foreach ($arr as $file) {
$exp = explode('/', $file);
$curr = &$result;
while (true) {
$chunk = array_shift($exp);
if (empty($exp)) {
$curr[] = $chunk;
break;
}
if (!isset($curr[$chunk])) {
$curr[$chunk] = array();
}
$curr = &$curr[$chunk];
}
}
var_dump($result);