0
我有一個包含模塊和子模塊的數據庫。在php中以遞歸方式創建關聯數組 - 「works」with echo
功能getChildren()
應該返回它們之間的關聯,以創建導航元素:
public function getChildren($id=0) {
$modulesResult = $this->find('all', array(
'conditions' => array('parent' => $id)
));
echo "<ul>";
foreach ($modulesResult as $key => $value) {
echo "<li>";
echo $value['module']['id'].". ".$value['module']['modulename'];
$this->getChildren($value['module']['id']);
echo "</li>";
}
echo "</ul>";
}
將會產生以下的輸出:
1. Calendar
2. Mailbox
3. Statistics
15. Local Statistics
16. Regiona Sstatistics
17. Global Statistics
18. Custom Statistical Reports
4. Production
19. Current Production
22. Sort By Product
23. Create Product
24. List Products
20. Production History
25. From-To
26. Yearly
27. Monthly
21. Projections
28. Analysis
5. Trade
29. E-store
30. Products
32. List Products
33. Create Product
34. Sort By Product
31. Dashboard
我想做同樣的事情 ,但不是回聲,我想把所有東西都放在一個社會陣列。
我嘗試這樣做:
public function getChildrenTest($id=0, $array=array()) {
pr($array);
$modulesResult = $this->find('all', array(
'conditions' => array('parent' => $id)
));
foreach ($modulesResult as $key => $value) {
#echo $value['module']['id'].$value['module']['modulename']."<br>";
$array[$value['module']['parent']][$value['module']['id']] = $value['module']['modulename'];
$this->getChildrenTest($value['module']['id'], $array);
}
return $array;
}
但它僅輸出前的水平,這樣的:
Array
(
[0] => Array
(
[1] => Calendar
[2] => Mailbox
[3] => Statistics
[4] => Production
[5] => Trade
)
)
我想上面的代碼,但沒有工作的幾個變化!似乎卡住了!
我是否失去了遞歸的一些信息?
由於看起來像什麼,我想,我會嘗試這一點,並標記你爲正確答案最終:d – Alexandros
找到一個更好的解決方案,您所創建的陣列亂:),不知道我是否應該正確地標記你:D – Alexandros
由此產生的數組是凌亂的,因爲方法很混亂。我們可以添加進一步的「後處理」來清理它,但是有更好的方法來處理嵌套數組。我已經編輯了包含'find('threaded')'的答案。隨時接受任何你認爲是最好的答案,它不一定是我的:) –