php 無限遞迴分類
阿新 • • 發佈:2018-12-29
$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'=>5), array('id'=>10,'name'=>'ios','pid'=>5), ); function my_category($categories, $pid=0){ $tree = array(); foreach($categories as $key=>$value){ if($value['pid'] == $pid){ $value['children'] = my_category($categories, $value['id']); if($value['children'] == null){ unset($value['children']); } $tree[] = $value; } } return $tree; } $tree = my_category($categories, 0); echo '<pre>';print_r($tree);exit;