<code>$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp']; </code>
根据这个数组,转成目录树的结构,如下:
aa
-bb
-kk
ww
-yyy
xx
-oo
--pp
<code>$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp']; </code>
根据这个数组,转成目录树的结构,如下:
aa
-bb
-kk
ww
-yyy
xx
-oo
--pp
<code class="php"><?php $paths = ['aa','aa/bb/bb','ww/yyy/bb','aa/kk','xx/oo/pp']; $arr = [];//先定义一个空数组用来存储所有路径。 //循环找出所有路径 foreach($paths as $v){ $path = explode('/',$v); $temp = ''; foreach($path as $k2=>$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</code>
为什么不弄成二维数组。
可以用无限极分类
想办法弄成这样
<code>元素 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 </code>
用无限极分类的思想
<code class="php">// 重排数组 $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 $v) { echo "$v$k<br>"; }</code>
<code> // 把这类数据转换成无限级格式... $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 </code>