用户
 找回密码
 入住 CI 中国社区
搜索
查看: 2584|回复: 3
收起左侧

两个foreach如何遍历出父类和子类在前台?

[复制链接]
发表于 2012-10-11 12:27:43 | 显示全部楼层 |阅读模式
两个foreach如何遍历出父类和子类在前台?


这是数据库表 数据



要在前台显示成




每个父类下面还在再遍历出子类的名字

这是控制器代码

            function show(){
               
                      $this->db->where(array('parent'=>0));   
                $data['parent']=$this->db->get('type')->result_array();
                //var_dump($data);
                foreach($data['parent'] as $value){
                        $id=$value['id'];
                        $this->db->where(array('parent'=>$id));
                        $data['child']=$this->db->get('type')->result_array();
                        
                }
                //var_dump($data);
                $this->load->view('templates/header');
                $this->load->view('index/index',$data);
                $this->load->view('templates/floor');
            }

不知道该怎么在前台遍历显示?求教

发表于 2012-10-11 12:48:25 | 显示全部楼层
本帖最后由 大道达人 于 2012-10-11 13:10 编辑
PHP复制代码
 
       $data = array();
       $parent = $this->db->where(array('parent'=>0))->get('type')->result_array();
       foreach ($parent as $value) {
           //获取子类
           $child = $this->db->select('type')->where(array('parent' => $value['id']))->get('type')->result_array();
           $data[$value['type']] = array_values($child);
       }  
 
复制代码
 楼主| 发表于 2012-10-11 16:08:32 | 显示全部楼层
大道达人 发表于 2012-10-11 12:48

谢谢了, 但是数组是这个结构,前台该怎么遍历呢?
array(4) {
  ["汽车"]=>
  array(2) {
    [0]=>
    array(1) {
      ["type"]=>
      string(9) "比亚迪"
    }
    [1]=>
    array(1) {
      ["type"]=>
      string(6) "奥拓"
    }
  }
  ["服装"]=>
  array(2) {
    [0]=>
    array(1) {
      ["type"]=>
      string(6) "美邦"
    }
    [1]=>
    array(1) {
      ["type"]=>
      string(6) "以纯"
    }
  }
  ["地产"]=>
  array(0) {
  }
前台我写成这样出不来哦
<ul>
    <?php foreach($data as $key=>$value): ?>
    <li><?php echo $key; ?></li>
    <?php echo $value['type']; ?>
    <?php endforeach;?>
</ul>
发表于 2012-10-12 09:53:56 | 显示全部楼层
继续、驕傲 发表于 2012-10-11 16:08
谢谢了, 但是数组是这个结构,前台该怎么遍历呢?
array(4) {
  ["汽车"]=>
  1.         foreach ($data as $key => $value)
  2.         {
  3.             echo "<li>$key</li>";
  4.             if ($value)
  5.             {
  6.                 echo "<ul>";
  7.                 foreach ($value as $v)
  8.                 {
  9.                     echo "<li>".$v['type']."</li>";
  10.                 }
  11.                 echo "</ul>";
  12.             }
  13.         }
  14.         echo "</ul>";

复制代码

本版积分规则