1 回答

TA貢獻1874條經驗 獲得超12個贊
最好的選擇是在數據庫的字段中指示級別,而不是一遍又一遍地動態計算它們。如果這不是一個選擇,那么......
我們將結果準備到帶有idfor 索引鍵的數組中并添加一個level字段:
$menu = [];
foreach($query as $row) {
$row->level = null;
$menu[$row->id] = $row;
}
一旦完成,剩下的就很簡單了:
foreach($menu as &$item) {
if (is_null($item->parent)) {
$item->level = 1;
} else {
$item->level = $menu[$item->parent]->level + 1;
}
}
換句話說:如果父項是null,則該項目的級別為 1。否則,它是其父項的級別 + 1。這會產生以下(顯示相關字段)數組:
array(17) {
[1] · object(stdClass)#2 (7) {
["title"] · string(4) "Home"
["parent"] · NULL
["level"] · int(1)
} ...
[6] · object(stdClass)#6 (7) {
["title"] · string(9) "Service 1"
["parent"] · int(3)
["level"] · int(2)
} ...
[15] · object(stdClass)#14 (7) {
["title"] · string(11) "Service 1.1"
["parent"] · int(6)
["level"] · int(3)
} ...
[17] · object(stdClass)#16 (7) {
["title"] · string(13) "Service 1.1.1"
["parent"] · int(15)
["level"] · int(4)
}
}
然后你就可以簡單地做str_repeat (" ", $item['level'])。不過,這里有一個需要注意的地方:如果您的菜單項“亂序”,即它將不起作用。如果在其父母之前有一個孩子。
- 1 回答
- 0 關注
- 105 瀏覽
添加回答
舉報