diff --git a/tree.php b/tree.php index 3c5e2e0..60b05bf 100644 --- a/tree.php +++ b/tree.php @@ -6,45 +6,56 @@ * Time: 13:46 */ - -$test_data = [ - ['id' => 0, 'name' => 'A'], - ['id' => 1, 'name' => 'a', 'pid' => 0], - ['id' => 2, 'name' => 'b', 'pid' => 1], - ['id' => 3, 'name' => 'c', 'pid' => 1], - ['id' => 4, 'name' => 'd', 'pid' => 5], - ['id' => 5, 'name' => 'e', 'pid' => 0], - ['id' => 6, 'name' => 'e', 'pid' => 4], +$arr = [ + ['id'=>1,'title'=>'first','pid'=>0,'level'=>1], + ['id'=>2,'title'=>'second','pid'=>0,'level'=>1], + ['id'=>3,'title'=>'third','pid'=>1,'level'=>2], + ['id'=>4,'title'=>'fourth','pid'=>1,'level'=>2], + ['id'=>5,'title'=>'fifth','pid'=>2,'level'=>2], + ['id'=>6,'title'=>'sixth','pid'=>3,'level'=>3], + ['id'=>7,'title'=>'seventh','pid'=>6,'level'=>4], + ['id'=>8,'title'=>'seventh','pid'=>7,'level'=>5], + ['id'=>9,'title'=>'seventh','pid'=>8,'level'=>6], + ['id'=>10,'title'=>'seventh','pid'=>8,'level'=>6], + ['id'=>11,'title'=>'seventh','pid'=>8,'level'=>6], ]; -function m_tree($arr, $pid = 0) -{ - $tree = []; - foreach ($arr as $t) { - if ($t['id'] == $pid) { - $tree = $t; - } - } - foreach ($arr as $child) { - if (isset($child['pid']) && $child['pid'] == $tree['id']) { - $tree['child'][] = $child; + +function tree($arr, $pid = 0, $level = 1){ + $child = []; + foreach($arr as $v){ + // $child:孩子 $v:孩子的孩子 $childNodes:孩子的孩子的孩子,也就是说,在这个函数里,要处理子孙三代 + if($v['pid'] == $pid){ // 得到子节点后递归得到子节点的子节点 + $childNodes = tree($arr, $v['id'], $level + 1); // get childNodes's childNodes + if($childNodes){ + $v['child'] = $childNodes; + $v['level'] = $level; + } + $child[] = $v; // $v is $child's child } } - foreach ($tree as $k1 => $v1) { - if (is_array($v1)) { - foreach ($v1 as $k2 => $v2) { - $tree['child'][$k2] = m_tree($arr, $v2['id']); - } + return $child; +} + +$tree = tree($arr,0); + +function html($tree, $level = 0){ + $str = ''; } -echo '
';
-print_r(m_tree($test_data));
-echo '
'; -die; +html($tree); -function tree($directory) +die; +function file_tree($directory) { $mydir = dir($directory); echo "