首先看代碼實現
function generateTree($items){ $tree = array(); foreach($items as $item){ if(isset($items[$item['pid']])){ $items[$item['pid']]['son'][] = &$items[$item['id']]; }else{ $tree[] = &$items[$item['id']]; } } return $tree; } $items = array( 1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'), 2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'), 3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'), 4 => array('id' => 4, 'pid' => 3, 'name' => '長豐縣'), 5 => array('id' => 5, 'pid' => 1, 'name' => '安慶市'), ); print_r(generateTree($items));
Array ( [0] => Array ( [id] => 1 [pid] => 0 [name] => 安徽省 [son] => Array ( [0] => Array ( [id] => 3 [pid] => 1 [name] => 合肥市 [son] => Array ( [0] => Array ( [id] => 4 [pid] => 3 [name] => 長豐縣 ) ) ) [1] => Array ( [id] => 5 [pid] => 1 [name] => 安慶市 ) ) ) [1] => Array ( [id] => 2 [pid] => 0 [name] => 浙江省 ) )
------------------------------------ 下面方框裡是上一個博主提出的問題,我沒看懂什麼意思 ,慚愧!-------------------------------------
上面生成樹方法還可以精簡到5行:
function generateTree($items){ foreach($items as $item) $items[$item['pid']]['son'][$item['id']] = &$items[$item['id']]; return isset($items[0]['son']) ? $items[0]['son'] : array(); }上面這種無限極分類數據樹形結構化的方法值得借鑒。但是我覺得這段代碼實際用途並不明顯啊,你想取出格式化的樹形數據還是要遞歸啊:
/** * 如何取數據格式化的樹形數據 */ $tree = generateTree($items); function getTreeData($tree){ foreach($tree as $t){ echo $t['name'].'不明白為什麼他還要遞歸取出,如果把generateTree()的返回值 輸出為json給前端不好嗎?
'; if(isset($t['son'])){ getTreeData($t['son']); } } } getTreeData($tree);