子类别PHP / MySQL的类别

时间:2012-02-06 07:07:59

标签: php mysql html codeigniter html-lists

我有MySql表名'类别',在该表中我有

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

我只想在html嵌套'ul'中显示这些数据,如

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

用php,请帮我用php(CodeIgniter)获取这些数据并显示。

1 个答案:

答案 0 :(得分:1)

以下是您的问题的三个组成部分:控制器,模型和视图......

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