在進行無限極分類中最常用的演算法就是“遞迴”,熟悉PHP語言的朋友肯定知道,PHP不擅長遞迴 ,而且遞迴次數有限(100次左右,因作業系統和配置而異)。
所以本文將會給大家帶來幾種不使用遞迴實現無限級分類的代碼。供大家來學習使用。
第一種:
無限級分類在開發中經常使用,例如:部門結構、文章分類。無限級分類的痛點在於“輸出”和“查詢”,例如
將文章分類輸出為<ul>列表形式;
尋找分類A下面所有分類包含的文章。
1.實現原理
幾種常見的實現方法,各有利弊。其中“改進前序走訪樹”資料結構,便於輸出和查詢,但是在移動分類和常規理解上有些複雜。
2.資料結構
<?php $list = array( array('id'=>1, 'fid'=>0, 'title' => '中國'), array('id'=>2, 'fid'=>1, 'title' => '江蘇'), array('id'=>3, 'fid'=>1, 'title' => '安徽'), array('id'=>4, 'fid'=>8, 'title' => '江陰'), array('id'=>5, 'fid'=>3, 'title' => '蕪湖'), array('id'=>6, 'fid'=>3, 'title' => '合肥'), array('id'=>7, 'fid'=>3, 'title' => '蚌埠'), array('id'=>8, 'fid'=>8, 'title' => '無錫') );?>
由於所有的遞迴均可以使用迴圈實現,本文根據PHP語言特點編寫了一套關於“無限級”分類的函數,相比遞迴實現而言效率更高。
3.輸出ul列表形式
將上述資料輸出為下面的HTML
<ul> <li class="first-child"> <p>江蘇</p> <ul> <li class="first-child last-child"> <p>無錫</p> <ul> <li class="first-child last-child"> <p>江陰</p> </li> </ul> </li> </ul> </li> <li class="last-child"> <p>安徽</p> <ul> <li class="first-child"><p>蕪湖</p></li> <li><p>合肥</p></li> <li class="last-child"><p>蚌埠</p></li> </ul> </li></ul>
這種HTML結構在前端使用(使用JavaScript和CSS構造可摺疊樹)十分方便。具體實現程式如下:
<ul><?php echo get_tree_ul($list, 1); ?></ul>
4.輸出option列表形式
<select> <option value="2">江蘇</option> <option value="8"> 無錫</option> <option value="4"> 江陰</option> <option value="3">安徽</option> <option value="5"> 蕪湖</option> <option value="6"> 合肥</option> <option value="7"> 蚌埠</option></select>
具體實現程式如下:
<select><?php // get_tree_option()返回數組,並為每個元素增加了“深度”(即depth)列,直接輸出即可 $options = get_tree_option($list, 1); foreach($options as $op) { echo '<option value="' . $op['id'] .'">' . str_repeat(" ", $op['depth'] * 4) . $op['title'] . '<;/option>'; }?><;/select>
5. 尋找某一分類的所有子類
<?php $children = get_tree_child($list, 0); echo implode(',', $children); // 輸出:1,3,2,7,6,5,8,4?>
6. 尋找某一分類的所有父類
<?php $children = get_tree_parent($list, 4); echo implode(',', $children); //8, 2, 10?>
7. 相關函數
<?phpfunction get_tree_child($data, $fid) { $result = array(); $fids = array($fid); do { $cids = array(); $flag = false; foreach($fids as $fid) { for($i = count($data) - 1; $i >=0 ; $i--) { $node = $data[$i]; if($node['fid'] == $fid) { array_splice($data, $i , 1); $result[] = $node['id']; $cids[] = $node['id']; $flag = true; } } } $fids = $cids; } while($flag === true); return $result;} function get_tree_parent($data, $id) { $result = array(); $obj = array(); foreach($data as $node) { $obj[$node['id']] = $node; } $value = isset($obj[$id]) ? $obj[$id] : null; while($value) { $id = null; foreach($data as $node) { if($node['id'] == $value['fid']) { $id = $node['id']; $result[] = $node['id']; break; } } if($id === null) { $result[] = $value['fid']; } $value = isset($obj[$id]) ? $obj[$id] : null; } unset($obj); return $result;} function get_tree_ul($data, $fid) { $stack = array($fid); $child = array(); $added_left = array(); $added_right= array(); $html_left = array(); $html_right = array(); $obj = array(); $loop = 0; foreach($data as $node) { $pid = $node['fid']; if(!isset($child[$pid])) { $child[$pid] = array(); } array_push($child[$pid], $node['id']); $obj[$node['id']] = $node; } while (count($stack) > 0) { $id = $stack[0]; $flag = false; $node = isset($obj[$id]) ? $obj[$id] : null; if (isset($child[$id])) { $cids = $child[$id]; $length = count($cids); for($i = $length - 1; $i >= 0; $i--) { array_unshift($stack, $cids[$i]); } $obj[$cids[$length - 1]]['isLastChild'] = true; $obj[$cids[0]]['isFirstChild'] = true; $flag = true; } if ($id != $fid && $node && !isset($added_left[$id])) { if(isset($node['isFirstChild']) && isset($node['isLastChild'])) { $html_left[] = '<li class="first-child last-child">'; } else if(isset($node['isFirstChild'])) { $html_left[] = '<li class="first-child">'; } else if(isset($node['isLastChild'])) { $html_left[] = '<li class="last-child">'; } else { $html_left[] = '<li>'; } $html_left[] = ($flag === true) ? "<p>{$node['title']}</p><ul>" : "<p>{$node['title']}</p>"; $added_left[$id] = true; } if ($id != $fid && $node && !isset($added_right[$id])) { $html_right[] = ($flag === true) ? '</ul></li>' : '</li>'; $added_right[$id] = true; } if ($flag == false) { if($node) { $cids = $child[$node['fid']]; for ($i = count($cids) - 1; $i >= 0; $i--) { if ($cids[$i] == $id) { array_splice($child[$node['fid']], $i, 1); break; } } if(count($child[$node['fid']]) == 0) { $child[$node['fid']] = null; } } array_push($html_left, array_pop($html_right)); array_shift($stack); } $loop++; if($loop > 5000) return $html_left; } unset($child); unset($obj); return implode('', $html_left);} function get_tree_option($data, $fid) { $stack = array($fid); $child = array(); $added = array(); $options = array(); $obj = array(); $loop = 0; $depth = -1; foreach($data as $node) { $pid = $node['fid']; if(!isset($child[$pid])) { $child[$pid] = array(); } array_push($child[$pid], $node['id']); $obj[$node['id']] = $node; } while (count($stack) > 0) { $id = $stack[0]; $flag = false; $node = isset($obj[$id]) ? $obj[$id] : null; if (isset($child[$id])) { for($i = count($child[$id]) - 1; $i >= 0; $i--) { array_unshift($stack, $child[$id][$i]); } $flag = true; } if ($id != $fid && $node && !isset($added[$id])) { $node['depth'] = $depth; $options[] = $node; $added[$id] = true; } if($flag == true){ $depth++; } else { if($node) { for ($i = count($child[$node['fid']]) - 1; $i >= 0; $i--) { if ($child[$node['fid']][$i] == $id) { array_splice($child[$node['fid']], $i, 1); break; } } if(count($child[$node['fid']]) == 0) { $child[$node['fid']] = null; $depth--; } } array_shift($stack); } $loop++; if($loop > 5000) return $options; } unset($child); unset($obj); return $options;}?>
第二種:
這是使用TP來製作的無限級分類。
演算法複雜度為T(n)=O(2n),只遍曆兩次數組.
關鍵代碼其實只有一行
$return[$v['pid']]['child'][$v['id']] = &$return[$k];
但是為了實現較為複雜的擴充,這裡添加一些額外的資訊
//索引要和ID一致,這不是廢話麼//pid是父元素//不要出現死迴圈嵌套,就是AB互為父子//不要出現相同name$list[0]=['id'=>0,'pid'=>-1,'name'=>'A@0'];//-1用於後面的根目錄判斷$list[1]=['id'=>1,'pid'=>0,'name'=>'A@1'];$list[2]=['id'=>2,'pid'=>0,'name'=>'A@2'];$list[3]=['id'=>3,'pid'=>2,'name'=>'A@3'];$list[4]=['id'=>4,'pid'=>3,'name'=>'A@4'];$list[5]=['id'=>5,'pid'=>0,'name'=>'A@5'];$list[6]=['id'=>6,'pid'=>1,'name'=>'A@6'];//先初始化目錄$return=[];foreach($list as $v) $return[$v['name']]=[];//將每個目錄與父目錄進行拼接,並找到根目錄foreach($list as $k=>$v){ if($v['pid']>=0) $return[$list[$v['pid']]['name']][$v['name']]=&$return[$v['name']]; else $parent=$v['name'];}//列印根目錄print_r($return[$parent]);
輸出1
Array( [A@1] => Array ( [A@6] => Array ( ) ) [A@2] => Array ( [A@3] => Array ( [A@4] => Array ( ) ) ) [A@5] => Array ( ))
代碼2
/** * Created by PhpStorm. * User: Nikaidou-Shinku * Date: 16/9/14 * Time: 17:12 */$list[] = ['id' => 0, 'pid' => -1, 'name' => 'A@0'];//-1用於後面的根目錄判斷$list[] = ['id' => 1, 'pid' => 0, 'name' => 'A@1'];$list[] = ['id' => 2, 'pid' => 0, 'name' => 'A@2'];$list[] = ['id' => 3, 'pid' => 2, 'name' => 'A@3'];$list[] = ['id' => 4, 'pid' => 3, 'name' => 'A@4'];$list[] = ['id' => 5, 'pid' => 0, 'name' => 'A@5'];$list[] = ['id' => 6, 'pid' => 1, 'name' => 'A@6'];//先初始化目錄$return = [];$parent = '';foreach ($list as $v) $return[$v['id']] = [ 'id' => $v['id'], 'name' => $v['name'], 'pid' => $v['pid'], 'child' => '', ];//將每個目錄與父目錄進行拼接,並找到根目錄foreach ($return as $k => $v) { if ($v['pid'] >= 0) $return[$v['pid']]['child'][$v['id']] = &$return[$k]; else $parent = &$return[$k];}//列印根目錄var_export($parent);
輸出2
$aa=[ 'id' => 0, 'name' => 'A@0', 'pid' => -1, 'child' => [ 1 => [ 'id' => 1, 'name' => 'A@1', 'pid' => 0, 'child' => [ 6 => [ 'id' => 6, 'name' => 'A@6', 'pid' => 1, 'child' => '', ], ], ], 2 => [ 'id' => 2, 'name' => 'A@2', 'pid' => 0, 'child' => [ 3 => [ 'id' => 3, 'name' => 'A@3', 'pid' => 2, 'child' => [ 4 => [ 'id' => 4, 'name' => 'A@4', 'pid' => 3, 'child' => '', ], ], ], ], ], 5 => [ 'id' => 5, 'name' => 'A@5', 'pid' => 0, 'child' => '', ], ], ]
第三種:
接下來這個無限級分類更為的簡單。可以簡化成使用5行代碼就可以完成。
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();}
但是上面的代碼有個問題就是對資料庫結構有點要求,每個節點要指明其父節點是誰,雖然實用性不高,但是還是能給大家帶來啟發,學習下不同類型的無限級分類。