duandao8607 2012-02-06 07:07
浏览 24
已采纳

子类别PHP / MySQL的类别

i have MySql Table name 'category', in that table i have

id   catname   parent_id
1    animals
2    vegs        
3    dog        1
4    cat        1
5    carrot     2

i just wanna display this data in html nested 'ul' like

<ul>
  <li>Animals
      <ul>
         <li>dog</li>
         <li>cat</li>
      </ul>
  </li>
  <li>Vegs
     <ul>
         <li>Carrot</li>
      </ul>
 </li>
</ul>

with php, please help me to get this data with php(CodeIgniter) and display.

  • 写回答

1条回答 默认 最新

  • dongsunny1113 2012-02-10 13:52
    关注

    Here are the three components for your question: controller, model and view...

    <!-- THE VIEW -->
    
    <ul>
    <?php foreach($main_cat->result() as $rowm) : ?>
    
        <li><?php echo $rowm->catname ?>
            <ul>
            <?php
                $id = $rowm->id;
                $sec_cat = $this->yourmodel->get_secondary($id);
                foreach($sec_cat->result() as $rows) :
            ?>
    
                <li><?php echo $rows->catname ?></li>
    
            <?php endforeach; ?>
            </ul>
        </li>
    
    <?php endforeach; ?>
    </ul>
    
    
    
    <!-- THE CONTROLLER -->
    
    <?php
    
    class Welcome extends CI_Controller {   
       function index()
       {
          $data['main_cat'] = $this->yourmodel->get_main();
          $this->load->view('welcome_view',$data);
       }
    } 
    ?>
    
    
    
      <!-- THE MODEL -->
    
    <?php
    class Yourmodel extends CI_Model {
    
    function get_main()
    {
        $this->db->where('parent_id','');
        $query = $this->db->get('category');
        return $query;
    }
    
    function get_secondary($parent)
    {
        $this->db->where('parent_id',$parent);
        $query = $this->db->get('category');
        return $query;
    }
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算