Algorithm - PHP converts an array of paths into a directory tree

WBOY
Release: 2016-10-11 14:23:12
Original
1406 people have browsed it

$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp']; 
Copy after login
Copy after login

According to this array, convert it into the structure of the directory tree, as follows:
aa
-bb
-kk
ww
-yyy
xx
-oo
--pp

Reply content:

$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp']; 
Copy after login
Copy after login

According to this array, convert it into the structure of the directory tree, as follows:
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; }
Copy after login

Why not make it a two-dimensional array.

Can be classified by Infinitus

Find a way to make it like this

元素 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 
Copy after login

Using the idea of infinite classification

// 重排数组 $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
"; }
Copy after login

 // 把这类数据转换成无限级格式... $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 
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!