在Codeigniter中显示嵌套列表

时间:2014-07-03 07:44:37

标签: php html mysql codeigniter

我的数据库中有以下表格:

projects(id, name)
subprojects(id, project_id, name)

我想在嵌套列表中显示项目及其子项目。这是一个例子:

<ul>
    <li><a href="#">Project</a></li>
    <li><a href="#">Project</a>
        <ul>
            <li><a href="#">Sub Project</a></li>
            <li><a href="#">Sub Project</a></li>
        </ul>
    </li>
</ul>

我使用CodeIgniter作为框架,实现结果的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

你应该在foreach中选择项目结果数组

$query = " select * from projects";
$query = $this->db->query($query);
$result = $query->result_array() ;
foreach($result as $key=>$value)
{
   $query = " select * from subprojects where project_id='".$value['id']."' ";
   $query = $this->db->query($query);
   $result[$key]['subproject'] = $query->result_array() ;
}

并在视图中

foreach($result as $row)
{
   echo " <li><a href='#'>".$row['name']."</a>";    
   if(isset($row['subproject']))
   {
    echo "<ul>";
    foreach($row['subproject'] as $sub)
    echo " <li><a href='#'>".$sub['name']."</a>";    
    echo "</ul>";
   }
   else
   {
    echo "</li>";
   }
}