简体   繁体   中英

Unable to retrieve the sub categories

Hello I have tried to make categories and sub categories and trying to call sub categories as --sub cat name because I placed the category and sub category in the same table is used nested option. But, that is not working for me.

Can anyone help me out this this categories are getting but unable to get sub categories

<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>

Try following function which should work for you and it is in core php so,you have to implement yourself in to 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; 
}

And call it as

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

hope it will help you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM