1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| <?php
header("content-type:text/html;charset=utf-8"); $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), );
$tree = array();
foreach($categories as $category){ $tree[$category['id']] = $category; $tree[$category['id']]['children'] = array(); }
foreach($tree as $key=>$item){ if($item['pid'] != 0){ $tree[$item['pid']]['children'][] = &$tree[$key]; if($tree[$key]['children'] == null){ unset($tree[$key]['children']); } } }
foreach($tree as $key=>$category){ if($category['pid'] != 0){ unset($tree[$key]); } }
print_r($tree);
$tree = $categories; function get_attr($a,$pid){ $tree = array(); foreach($a as $v){ if($v['pid'] == $pid){ $v['children'] = get_attr($a,$v['id']); if($v['children'] == null){ unset($v['children']); } $tree[] = $v; } } return $tree; } echo "<br/><br/><br/>";
print_r(get_attr($tree,0));
|