Как создать представление списка из таблицы базы данных? - PullRequest
1 голос
/ 09 мая 2020

Я запрашиваю таблицу категорий id, parent_id, name, чтобы создать список всех категорий и подкатегорий. На данный момент у меня есть:

  • HP
    • Ноутбуки
    • P C
  • Спорт
    • Солнечные очки
  • Еда
  • Дом

Функция, которую я использую для генерации вывода:

public function get_category($parent_id = NULL)
{ 
    $query = $this->db->get_where('category', array('parent_id' => $parent_id))->result();
    $result = '';

    foreach ($query as $row)
    {
        $i = 0;

        if ($i == 0) 
        {
            $result .= '<ul>';  
        }

        $result .= '<li><a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name;
        $result .= $this->get_category($row->id);
        $result .= '</li>';

        $i++;

        if ($i > 0) 
        {
            $result .= '</ul>';
        }
    }

    return $result;
}

Вот чего я хочу добиться:

HP
HP > Laptops
HP > PC
Sports
Sports > Sunglasses
Food
House

Ответы [ 2 ]

1 голос
/ 09 мая 2020

Попробуйте следующее

public function get_category($parent_id = NULL,$level, $prev = "")
{ 
    $query = $this->db->get_where('category', array('parent_id' => $parent_id))->result();
    $result = '';

    foreach ($query as $row)
    {
       $temp = $prev;
       if($level == 0){
        $temp .= '<a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name.'</a>';
       }else{
        $temp .= ' &gt; <a href="'.base_url().'category/edit/'.$row->id.'">' . $row->name.'</a>';
       }
        $result .= $temp;
        $result .= "<br />";
        $result .= $this->get_category($row->id, $level + 1, $temp);

    }

    return $result;
}

Первый запуск этой функции должен быть

get_category(NULL, 0, "");

Здесь

  • NULL - родительский идентификатор (вы можете использовать al oop для динамического прохода id)
  • level должно быть 0
  • prev должно быть пустым
0 голосов
/ 09 мая 2020

Я создал демо-версию в соответствии с вашими потребностями, и она мне понравилась. Я делюсь приведенным ниже кодом, я объяснил в комментариях, где это необходимо. Посмотри, поможет ли это тебе.

Контроллер

public function get_category($parent_id = NULL){ 

    // get the {category}, {sub_category} from the table, if {sub_category} stored in different table use {JOIN}
    $data['category'] = $this->db->get_where('category', array('parent_id' => $parent_id))->result();  

    $this->load->view('your-view', $data); 
}

Просмотр

<?php 

if(!empty($category)){ // check if {$category} has value; if not, do nothing

    $catArr = array();  // initialize array to store category id

?>

<ul>  <!-- Start ul -->

<?php 

    foreach($category as $cat){ //loop through all the {category} array

        // check if the {cat_id} already exists in array; if not, do so where {cat_id} is category id(change your value here)
        if( ! in_array( $cat->cat_id, $catArr ) ){ 

            $catArr[] = $cat->event_id;

        ?>  

        <li><?php echo $cat->cat_name; ?></li>  <!-- show {cat_name} in list -- your category name here -->

        <?php

        }

        ?>

    <!-- Show {cat_name} and {subcat_name} both -- (your values here). Give links or whatever here(your styling)-->
    <li><?php echo $cat->cat_name; ?> &gt; <?php echo $cat->subcat_name; ?></li>

    <?php

    } 

    ?>

</ul>

<?php 

} 

?>

ВЫХОД

Honda
Honda > Car
Honda > Bike
Philips 
Philips > Electricals
Philips > Electronics
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...