1 <?php 2 function tree($arr, $pid=0, $level=0){ 3 static $list = array(); 4 foreach($arr as $v){ 5 if($v['parent_id'] == $pid){ 6 $v['level'] = $level; 7 $list[] = $v; 8 tree($arr, $v['cat_id'], $level+1); 9 } 10 } 11 return $list; 12 } 13 14 $arr = array(); 15 $conn = mysql_connect("localhost", "root", ""); 16 mysql_select_db("test"); 17 mysql_query("set names utf8"); 18 $result = mysql_query("select * from category"); 19 $i=0; 20 while($res = mysql_fetch_assoc($result)){ 21 $arr[$i]['cat_id'] = $res['cat_id']; 22 $arr[$i]['cat_name'] = $res['cat_name']; 23 $arr[$i]['parent_id'] = $res['parent_id']; 24 $i = $i + 1; 25 } 26 $jieshu = tree($arr); 27 echo "<pre>"; 28 print_r($jieshu); 29 echo "</pre>"; 30 ?>