Home >Backend Development >PHP Tutorial >Algorithm - PHP converts an array of paths into a directory tree

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

WBOY
WBOYOriginal
2016-10-11 14:23:121496browse

<code>$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp'];
</code>

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:

<code>$paths = ['aa','aa/bb','ww/yyy','aa/kk','xx/oo/pp'];
</code>

According to this array, convert it into the structure of the directory tree, as follows:
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<$n;$i++){
        $line .= '-';
    }
    return $line;
}</code>

Why not make it a two-dimensional array.

Can be classified by Infinitus

Find a way to make it like this

<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>

Using the idea of ​​infinite classification

<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 < $k1; $i++) {
            $res[$v1] .= '-';
        }
    }
}
// 输出
foreach ($res as $k => $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>
Statement:
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