本文主要介紹了php生成無限欄目樹的相關知識。具有很好的參考價值。下面跟著小編一起來看下吧
欄位陣列:
#$arr=Array( Array('cid' => 2,'cname' => '新闻','pid' => 0), Array('cid' => 4,'cname' =>'体育','pid' => 0), Array('cid' => 5,'cname' => '娱乐','pid' => 0), Array('cid' => 7,'cname' => '热点新闻','pid' =>2), Array('cid' => 8,'cname' => '小众新闻','pid' => 2), Array('cid' => 9,'cname' => '民谣新闻','pid' => 8), );
'pid','id'=>'id','children'=>'children')){ $arr = array(); foreach ($array as &$v) { if ($v[$field['pid']] == $pid) { $v['level'] = $level; $tem = formatTree($array, $v[$field['id']],$v['level']+1,$field); //判断是否存在子数组 $tem && $v[$field['children']] = $tem; $arr[] = $v; } } return $arr; } $tree = formatTree( $arr,0,1, $field = array('pid'=>'pid','id'=>'cid','children'=>'children') ); echo ''; print_r( $tree); ?>登入後複製
以下主要介紹了PHP超牛逼無限極分類生成樹方法,巧用PHP中的引用實作樹的生成方法,比遞歸方法高階多了,需要的朋友可以參考下
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'].'<br>'; if(isset($t['son'])){ getTreeData($t['son']); } } } getTreeData($tree);
以上是php產生無限欄位樹_php技巧的詳細內容。更多資訊請關注PHP中文網其他相關文章!