php非遞迴實現無限極分類
阿新 • • 發佈:2021-12-17
一、陣列
$categories = array( array('id'=>1,'name'=>'陝西','parent_id'=>0), array('id'=>2,'name'=>'西安','parent_id'=>1), array('id'=>3,'name'=>'長安區','parent_id'=>2), array('id'=>4,'name'=>'河南','parent_id'=>0), array('id'=>5,'name'=>'鄭州','parent_id'=>4), array('id'=>6,'name'=>'河北','parent_id'=>0), array('id'=>7,'name'=>'石家莊','parent_id'=>6), array('id'=>8,'name'=>'新華區','parent_id'=>7));
二、非遞迴實現無限極分類
function getTree($categories) { //第一步,將分類id作為陣列key,並建立node單元 $tree = array(); foreach($categories as $category){ $tree[$category['id']] = $category; $tree[$category['id']]['node'] = array(); } //第二步,利用引用,將每個分類新增到父類node陣列中,這樣一次遍歷即可形成樹形結構。 foreach($tree as $key=>$item){ if($item['parent_id'] != 0){ $tree[$item['parent_id']]['node'][] = &$tree[$key];//注意:此處必須傳引用否則結果不對 if($tree[$key]['node'] == null){ unset($tree[$key]['node']); //如果node為空,則刪除該node元素 } } } //第三步,刪除無用的非根節點資料 foreach($tree as $key=>$category){ if($category['parent_id'] != 0){ unset($tree[$key]); } } return $tree; }
三、效果
Array ( [1] => Array ( [id] => 1 [name] => 陝西 [parent_id] => 0 [node] => Array ( [0] => Array ( [id] => 2 [name] => 西安 [parent_id] => 1 [node] => Array ( [0] => Array ( [id] => 3 [name] => 長安區 [parent_id] => 2 ) ) ) ) ) [4] => Array ( [id] => 4 [name] => 河南 [parent_id] => 0 [node] => Array ( [0] => Array ( [id] => 5 [name] => 鄭州 [parent_id] => 4 ) ) ) [6] => Array ( [id] => 6 [name] => 河北 [parent_id] => 0 [node] => Array ( [0] => Array ( [id] => 7 [name] => 石家莊 [parent_id] => 6 [node] => Array ( [0] => Array ( [id] => 8 [name] => 新華區 [parent_id] => 7 ) ) ) ) ) )程式碼改變世界!