php無限級樹狀分類
<?php //準備陣列,代替從資料庫中檢索出的資料(共有三個必須欄位id,name,pid) 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(); //第一步,將分類id作為陣列key,並建立children單元 foreach($categories as $category){ $tree[$category['id']] = $category; $tree[$category['id']]['children'] = array(); } //第二步,利用引用,將每個分類新增到父類children陣列中,這樣一次遍歷即可形成樹形結構。 foreach($tree as $key=>$item){ if($item['pid'] != 0){ $tree[$item['pid']]['children'][] = &$tree[$key];//注意:此處必須傳引用否則結果不對 if($tree[$key]['children'] == null){ unset($tree[$key]['children']); //如果children為空,則刪除該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']); //如果子元素為空則unset()進行刪除,說明已經到該分支的最後一個元素了(可選) } $tree[] = $v; //將記錄存入新陣列 } } return $tree; //返回新陣列 } echo "<br/><br/><br/>"; print_r(get_attr($tree,0)); 原文:https://blog.csdn.net/qishouzhang/article/details/47204359