时间:2021-07-01 10:21:17 帮助过:5人阅读
$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp'];
根据这个数组,转成目录树的结构,如下:
aa
-bb
-kk
ww
-yyy
xx
-oo
--pp
$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp'];
根据这个数组,转成目录树的结构,如下:
aa
-bb
-kk
ww
-yyy
xx
-oo
--pp
$v2){
$temp .= empty($temp)?$v2:'/'.$v2;
$arr[$temp] = $temp;
}
}
sort($arr); //排序
//循环
输出
foreach($arr as $v){
$path = explode('/',$v);
$n = count($path);
echo line($n).$path[$n-1]."\n";
}
function line($n){
$line = '';
for($i=1;$i<$n;$i++){
$line .= '-';
}
return $line;
}
为什么不弄成二维数组。
可以用无限极分类
想办法弄成这样
元素 id pid
aa 1 0
bb 2 1
ww 3 0
yyy 4 3
kk 5 1
xx 6 0
oo 7 6
pp 8 7
用无限极分类的思想
// 重排数组
$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp'];
sort($paths);
// 得到结果数组:k为值,v为前面-
$res = [];
foreach ($paths as $v) {
// 拆分路径
$path = explode('/', $v);
foreach ($path as $k1 => $v1) {
// 此项前面几个-
$res[$v1] = '';
for ($i=0; $i < $k1; $i++) {
$res[$v1] .= '-';
}
}
}
//
输出
foreach ($res as $k => $v) {
echo "$v$k
// 把这类数据转换成无限级格式...
$paths = ['aa','aa/bb/bb','ww/yyy/bb','aa/kk','xx/oo/pp'];
$data = [];
$id = 0;
foreach($paths as $path){
$tmps = explode('/', $path);
$parent = '';
foreach($tmps as $v){
$parentID = $parent == '' ? 0 : $data[$parent]['id'];
$parent .= $parent == '' ? $v : '/' . $v;
if( ! isset($data[$parent]) ){
$id++;
$tmp = array(
'id' => $id,
'parent_id' => $parentID,
'key' => $v,
'path' => $parent,
);
$data[$parent] = $tmp;
}
}
}
print_r($data);
// 再以无限级方式处理数据 $data