您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)如何在PHP中實(shí)現(xiàn)一個(gè)無(wú)限級(jí)分類(lèi),可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
不用遞歸實(shí)現(xiàn)無(wú)限級(jí)分類(lèi),簡(jiǎn)單測(cè)試了下性能比遞歸稍好一點(diǎn)點(diǎn)點(diǎn),但寫(xiě)得太復(fù)雜了,還是遞歸簡(jiǎn)單方便點(diǎn)
代碼:
<?php $list = array( array('id'=>1, 'pid'=>0, 'deep'=>0, 'name'=>'test1'), array('id'=>2, 'pid'=>1, 'deep'=>1, 'name'=>'test2'), array('id'=>3, 'pid'=>0, 'deep'=>0, 'name'=>'test3'), array('id'=>4, 'pid'=>2, 'deep'=>2, 'name'=>'test4'), array('id'=>5, 'pid'=>2, 'deep'=>2, 'name'=>'test5'), array('id'=>6, 'pid'=>0, 'deep'=>0, 'name'=>'test6'), array('id'=>7, 'pid'=>2, 'deep'=>2, 'name'=>'test7'), array('id'=>8, 'pid'=>5, 'deep'=>3, 'name'=>'test8'), array('id'=>9, 'pid'=>3, 'deep'=>2, 'name'=>'test9'), ); function resolve($list) { $newList = $manages = $deeps = $inDeeps = array(); foreach ($list as $row) { $newList[$row['id']] = $row; } $list = null; foreach ($newList as $row) { if (! isset($manages[$row['pid']]) || ! isset($manages[$row['pid']]['children'][$row['id']])) { if ($row['pid'] > 0 && ! isset($manages[$row['pid']]['children'])) $manages[$row['pid']] = $newList[$row['pid']]; $manages[$row['pid']]['children'][$row['id']] = $row; } if (! isset($inDeeps[$row['deep']]) || ! in_array($row['id'], $inDeeps[$row['deep']])) { $inDeeps[$row['deep']][] = array($row['pid'], $row['id']); } } krsort($inDeeps); array_shift($inDeeps); foreach ($inDeeps as $deep => $ids) { foreach ($ids as $m) { // 存在子欄目的進(jìn)行轉(zhuǎn)移 if (isset($manages[$m[1]])) { $manages[$m[0]]['children'][$m[1]] = $manages[$m[1]]; $manages[$m[1]] = null; unset($manages[$m[1]]); } } } return $manages[0]['children']; }
遞歸實(shí)現(xiàn)
function resolve2(& $list, $pid = 0) { $manages = array(); foreach ($list as $row) { if ($row['pid'] == $pid) { $manages[$row['id']] = $row; $children = resolve2($list, $row['id']); $children && $manages[$row['id']]['children'] = $children; } } return $manages; }
看完上述內(nèi)容,你們對(duì)如何在PHP中實(shí)現(xiàn)一個(gè)無(wú)限級(jí)分類(lèi)有進(jìn)一步的了解嗎?如果還想了解更多知識(shí)或者相關(guān)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。