在 php 中递归创建关联数组 -- "works" with echo

Create associative array recursively in php -- "works" with echo

我有一个包含模块和子模块的数据库。

函数getChildren()应该return它们之间的关联以创建导航元素:

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

我想做同样的事情, 但是不是echo, 我想把所有东西都放在一个关联数组中。

我试过这个:

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
        )
)

我尝试了上面代码的几种变体,但没有任何效果!好像卡住了!

我是否丢失了一些有关递归的信息?

尝试以下操作:

public function getChildren($id=0) {
    $modulesResult = $this->find('all', array(
        'conditions' => array('parent' => $id)
    ));

    $array=[];
    foreach ($modulesResult as $key => $value) {

        $array[$value['module']['id']]=array(
            $value['module']['modulename']=>$this->getChildren($value['module']['id'])
        );
    }

    return $array;
}

或者您也可以使用 find('threaded'),这是 CakePHP 提供的用于处理嵌套结果的查找器:

$modulesResult = $this->find('threaded',['parent'=>'parent']);

等于:

$modulesResult = $this->find('all');
$modulesResult = Hash::nest($modulesResult,['parentPath'=>'{n}.module.parent']);

参见: