0 =>
array (size=12)
'id' => string '1' (length=1)
'name' => string 'Test' (length=13)
'parent_id' => string '0' (length=1)
'path' => string '0,' (length=2)
'order' => string '100' (length=3)
'from' => string '0' (length=1)
'qyid' => null
'lng' => string '103.86182' (length=9)
'lat' => string '36.053103' (length=9)
'level' => null
'desc' => null
'level_code' => null
1 =>
array (size=12)
'id' => string '46' (length=2)
'name' => string 'Test2' (length=9)
'parent_id' => string '1' (length=1)
'path' => string '0,1' (length=3)
'order' => string '0' (length=1)
'from' => string '0' (length=1)
'qyid' => null
'lng' => null
'lat' => null
'level' => null
'desc' => null
'level_code' => null
我有如上的一個數組,其中parent_id代表該節點的父節點。我現在打算生成一棵樹。我接到前端的html如下:

Test
- Test2
html無限級分類前端輸出輸出,無限級分類問題 - Test3
html無限級分類前端輸出輸出,無限級分類問題 - Test4
html無限級分類前端輸出輸出,無限級分類問題
-
大家也可以忽略上面的html。
那麼遞歸該怎麼寫呢??? 虛心求教~~
回答:
首先,你需要一個樹的資料結構來按照一定的結構來組織你的資料,這個樹當中的每個節點用如下的TreeNode來表示,然後遞歸的周遊你的資料,在周遊的過程中動态的生成這個由TreeNode組成的樹。并傳回到前台。在前台再周遊一下,就能組成你要的效果了
public class TreeNode {
'id' => string '1' (length=1)
'name' => string 'Test' (length=13)
'parent_id' => string '0' (length=1)
'path' => string '0,' (length=2)
'order' => string '100' (length=3)
'from' => string '0' (length=1)
'qyid' => null
'lng' => string '103.86182' (length=9)
'lat' => string '36.053103' (length=9)
'level' => null
'desc' => null
'level_code' => null
public List nodes;
}
回答:
無限級json的功能估計是菜單了。
和樓上說的差不多,建個多叉樹。你想要的結果就是多叉樹前序周遊之後的結果。python的我實作過~~php的隻能提供解決方案了~(如果兄弟之間要求有序的話還需要加其他的操作)找到一個php的
希望有幫助。
回答:
我也正在做這個功能,終于弄出來了
我的資料庫結構
實作的效果
貼代碼
def _load_menuTree(self):
'加載系統菜單'
menus = api.resource.Resource().all(fields='id, pid, menu_name, resource_uri', display = 'S')
_items = {r.id:r for r in menus}
_items = defaultdict(hash, _items)
for k, r in _items.items():
r['children'] = deque()
retval = deque()
for k, r in _items.items():
if r.pid in _items:
_items[r.pid]['children'].append(_items[r.id])
else:
retval.append(_items[r.id])
return retval