donglu7998
2016-01-17 15:06
浏览 37
已采纳

在php中递归创建关联数组 - 使用echo“工作”

I have a database with modules and submodules.

The function getChildren() is supposed to return the association between them to create a navigation element:

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>";
    }

Which produces the following output:

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

I want to do the same thing, but instead of echo, I want to put everything in an associative array.

I tried this:

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;
    }

But it outputs only the first level, like this:

Array
(
    [0] => Array
        (
            [1] => Calendar
            [2] => Mailbox
            [3] => Statistics
            [4] => Production
            [5] => Trade
        )
)

I tried several variations of the code above but nothing works! Seems am stuck!

Am I losing some information on the recursion?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题