无法检索子类别

时间:2015-12-23 10:02:42

标签: php codeigniter

您好我尝试制作类别和子类别并尝试将子类别调用为--sub cat name,因为我将类别和子类别放在同一个表中使用了嵌套选项。但是,这对我不起作用。

任何人都可以帮我解决这个问题,这些类别正在增加但无法获得子类别

<select name="category" class="dropdown">
    <?php
        $query1 = $this->db->query('SELECT * FROM categories');
        foreach($query1->result() as $cat_name) {
            if($cat_name->cat_name == $cat_name->parent)
                echo "<option>". $cat_parent = $cat_name->cat_name."</option>";
                $query2 = $this->db->query("SELECT * FROM categories WHERE parent = '$cat_parent '");
                foreach($query2->result() as $sub_cat) {
                    if($sub_cat->cat_name != $sub_cat->parent) {
                        echo "<option> --" . $sub_cat->cat_name . "</option>";
                    }
                }
        }
    ?>
</select>

1 个答案:

答案 0 :(得分:2)

尝试以下适用于您的功能,它位于核心php中,因此,您必须自己实现codeigniter

function fetchCategoryTreeList($parent = 0, $user_tree_array = '') {
global $con;
if (!is_array($user_tree_array))
$user_tree_array = array();

$sql = "SELECT * FROM `location` WHERE 1 AND `parent_id` = $parent ORDER  BY id ASC";
$result=$con->query($sql);

if (mysqli_num_rows($result) > 0)
{
  $user_tree_array[] = "<ul>";
  while ($row =$result->fetch_object())
  {
   $user_tree_array[] = "<li>". $row->name."</li>";
   $user_tree_array = fetchCategoryTreeList($row->id, $user_tree_array);
  }
  $user_tree_array[] = "</ul><br/>";
}
return $user_tree_array; 
}

并将其命名为

$res = fetchCategoryTreeList();
foreach ($res as $r)
{
  echo  $r;
}

希望它会帮助你