如果一个问题我现在想解决几个小时,但根本找不到解决方案。
如果路径的单个阵列
$singleArray = array(
'/Web',
'/Web/Test1',
'/Web/Test2',
'/Web/Test2/Subfolder',
'/Web/Test3',
'/Public'
);
我想从这个数组中创建一个多维数组,它保留键,但将子文件夹放在正确的父文件夹中。稍后我想在新数组上循环以创建文件夹树(但这不是问题(
新阵列应该是这样的:
$multiArray = array(
'/Web'=>array(
'/Web/Test1'=>array(),
'/Web/Test2'=>array(
'/Web/Test2/Subfolder'=>array()
),
'/Web/Test3'=>array()
),
'/Public'=>array()
);
下面的代码将生成您想要的数组。解决问题的关键是在每次迭代中创建对数组的引用。
<?php
$singleArray = array(
'/Web',
'/Web/Test1',
'/Web/Test2',
'/Web/Test2/Subfolder',
'/Web/Test3',
'/Public'
);
$multiArray = array();
foreach ($singleArray as $path) {
$parts = explode('/', trim($path, '/'));
$section = &$multiArray;
$sectionName = '';
foreach ($parts as $part) {
$sectionName .= '/' . $part;
if (array_key_exists($sectionName, $section) === false) {
$section[$sectionName] = array();
}
$section = &$section[$sectionName];
}
}
成功了!伟大的挑战!
首先,我按照文件夹的数量对数组进行排序,这样第一个要处理的是那些文件夹最少的(根目录中(。
然后,函数遍历每个数组项和该项中的每个文件夹,将其与数组中的现有项进行比较,如果存在,则将其作为多维数组放置在该项中。
这最多适用于两个子文件夹/root/sub1/sub2,但它非常简单,添加功能以供深入使用非常简单。
此示例代码还打印出前/后数组:
$singleArray = array(
'/Web',
'/Web/Test1',
'/Web/Test2',
'/Web/Test2/Subfolder',
'/Web/Test3',
'/Public'
);
echo "<pre>";
print_r($singleArray);
$multiArray = array();
//first sort array by how many folders there are so that root folders are processed first
usort($singleArray, function($a, $b) {
$a_folders = explode("/", $a);
$b_folders = explode("/", $b);
$a_num = count($a_folders); //number of folders in first
$b_num = count($b_folders); //number of folders in second
if($a_num > $b_num) return -1;
elseif($a_num < $b_num) return 1;
else return 0;
});
//foreach in array
foreach($singleArray as $item){
//get names of folders
$folders = explode("/", $item);
//if the first folder exists
if(in_array($folders[0], $multiArray)){
$key1 = array_search($folders[0], $multiArray);
//repeat for subfolder #1
if(in_array($folders[1], $multiArray[$key1])){
$key2 = array_search($folders[1], $multiArray[$key1]);
//repeat for subfolder #2
if(in_array($folders[2], $multiArray[$key1][$key2])){
$key3 = array_search($folders[2], $multiArray[$key1][$key2]);
array_push($multiArray[$key1][$key2][$key3], $item);
} else array_push($multiArray[$key1][$key2], $item);
} else array_push($multiArray[$key1], $item);
} else array_push($multiArray, $item);
}
//reverse the array so that it looks nice
$multiArray = array_reverse($multiArray);
print_r($multiArray);
这将输出:
Array
(
[0] => /Web
[1] => /Web/Test1
[2] => /Web/Test2
[3] => /Web/Test2/Subfolder
[4] => /Web/Test3
[5] => /Public
)
Array
(
[0] => /Web
[1] => /Public
[2] => /Web/Test1
[3] => /Web/Test2
[4] => /Web/Test3
[5] => /Web/Test2/Subfolder
)