2012-02-06 95 views
1

我有MySQL表名 '類別',在該表中,我有類別與子類別的PHP/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

這個問題已經在這裏做了好幾次。請使用該網站的「搜索」功能。 – 2012-02-06 07:19:35

+0

例如:http://stackoverflow.com/questions/2871861/how-to-build-unlimited-level-of-menu-through-php-and-mysql/ - 然後在右鍵菜單中看到「相關」問題,這一方獲得許多類似的問題/答案。 – 2012-02-06 07:24:00

回答

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; 
} 
} 
?> 
+0

謝謝,它真的很有幫助。它的工作完美 – 2012-03-18 08:51:46