【问题标题】:Category with Subcategory PHP/MySQL带有子类别 PHP/MySQL 的类别
【发布时间】:2012-02-10 21:52:23
【问题描述】:

我有 MySql 表名'category',在那个表中我有

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)获取这些数据并显示。

【问题讨论】:

  • 这个问题已经在这里提出了好几次了。请使用网站的“搜索”功能。
  • 例如:stackoverflow.com/questions/2871861/… - 并查看此问题右侧的“相关”问题以获得许多类似的问题/答案。

标签: php mysql html codeigniter html-lists


【解决方案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;
}
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-30
    • 1970-01-01
    • 2011-06-05
    • 2017-06-17
    • 2010-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多