标签:
第1种:递归来实现
作者:魔天06
原文链接:http://blog.sina.com.cn/s/blog_5fb90aaa01015y3a.html
<?php //数组 //parentid是父类的id $rows = array( array( ‘id‘ => 1, ‘name‘ => ‘dev‘, ‘parentid‘ => 0 ), array( ‘id‘ => 2, ‘name‘ => ‘php‘, ‘parentid‘ => 1 ), array( ‘id‘ => 3, ‘name‘ => ‘smarty‘, ‘parentid‘ => 2 ), array( ‘id‘ => 4, ‘name‘ => ‘life‘, ‘parentid‘ => 0 ), array( ‘id‘ => 5, ‘name‘ => ‘pdo‘, ‘parentid‘ => 2 ), array( ‘id‘ => 6, ‘name‘ => ‘pdo-mysql‘, ‘parentid‘ => 5 ), array( ‘id‘ => 7, ‘name‘ => ‘java‘, ‘parentid‘ => 1 ) ); //无限极分类 function tree($arr, $pid, $tmp){ $tmp=$tmp." "; for($i=0; $i<count($arr); $i++){ if($arr[$i]["parentid"]==$pid){ echo $tmp."|--<a href=".$arr[$i]["id"].">".$arr[$i]["name"]."</a><br/>"; tree($arr, $arr[$i]["id"], $tmp); } } } tree($rows, ‘0‘, ‘‘); ?>
第2种:用键值和引用来处理,不用递归
作者:吾爱
原文链接:http://www.ekan001.com/articles/25
<?php $categories = array( array(‘id‘=>1,‘name‘=>‘电脑‘,‘pid‘=>0), array(‘id‘=>2,‘name‘=>‘手机‘,‘pid‘=>0), array(‘id‘=>3,‘name‘=>‘笔记本‘,‘pid‘=>1), array(‘id‘=>4,‘name‘=>‘台式机‘,‘pid‘=>1), array(‘id‘=>5,‘name‘=>‘智能机‘,‘pid‘=>2), array(‘id‘=>6,‘name‘=>‘功能机‘,‘pid‘=>2), array(‘id‘=>7,‘name‘=>‘超级本‘,‘pid‘=>3), array(‘id‘=>8,‘name‘=>‘游戏本‘,‘pid‘=>3), array(‘id‘=>9,‘name‘=>‘普通台式机‘,‘pid‘=>4), array(‘id‘=>10,‘name‘=>‘高级台式机‘,‘pid‘=>4) ); $tree = array(); //第一步,将分类id作为数组key,并创建children单元 foreach($categories as $category){ $tree[$category[‘id‘]] = $category; $tree[$category[‘id‘]][‘children‘] = array(); } //第二部,利用引用,将每个分类添加到父类children数组中,这样一次遍历即可形成树形结构。 foreach ($tree as $k=>$item) { if ($item[‘pid‘] != 0) { $tree[$item[‘pid‘]][‘children‘][] = &$tree[$k]; } } echo ‘<pre>‘; print_r($tree); ?>
标签:
原文地址:http://www.cnblogs.com/ken2016/p/5087926.html