Sort Listing by parent mysql data item in php

1

I have a listing to do that will work as follows:

<li id="1">Pai
    <ul>
        <li id="2">Item 01</li>
        <li id="3">Item 02
            <ul>
                <li id="4">Item 03</li>
            </ul>
        </li>
    </ul>
</li>

The data is retrieved from a Mysql table in the following format:

ID  ||  titulo    ||    pai
1   ||  Pai       ||    0
2   ||  Item 01   ||    1
3   ||  Item 02   ||    1
4   ||  Item 03   ||    3

The 'parent' field is based on the item ID.

How do I organize this via PHP?

    
asked by anonymous 07.05.2018 / 07:13

1 answer

0

You need to use a recursive function that shows all descending elements of the level that is passed in the function.

Below is my code that shows a menu in the same way that you want it. You need to remove what does not matter.

Note that my function QSelect returns the recordset of the query that is passed.

function menuTree($nivel, $id,$CAT) {

    $aCAT=explode('_',$CAT);
    $nivel++;
    $query="SELECT category_id,name  FROM categories WHERE is_active=1 and category_id_parent = $id order by sort,name asc ;";
    $QSelect=QSelect($query,0);
    $link='';

    $class_nivel_index=$nivel; //Como não ha classes para todos os niveis, isto vai limitar as opções
    if ($class_nivel_index>2){$class_nivel_index=2;}

    $class_menu=array('vertical-menu','sub-vertical-menu','sub-sub-vertical-menu');
    $class_menu_active=array('vertical-menu-active','sub-vertical-menu-active','sub-sub-vertical-menu-active');


    for ($r = 0; $r <= $nivel; $r++) {$link .=$aCAT[$r].'_';}
    {

        if($QSelect[0]['category_id']>0)
        {foreach ($QSelect as $row) {
            $linkCAT=$link . $row['category_id'];

            if (isset($aCAT[$nivel+1]) and $aCAT[$nivel+1]==intval($row['category_id'])){
                $Class=$class_menu_active[$class_nivel_index];
            }else{
                $Class=$class_menu[$class_nivel_index];

            }

            echo '<a href="/?OP=INDEX_SHOPPING&CAT=' . $linkCAT . '">';
            echo '<p class="' . $Class.'">';
                echo $row['name'];
            echo '</p>';
            echo '</a>';
            if (isset($aCAT[$nivel+1]) and $aCAT[$nivel+1]==intval($row['category_id'])){
                    menuTree($nivel, $row['category_id'],$CAT . '_' . $row['category_id']);
            }
        }
        }
    }
}

Main program call:

menuTree(-1,0,$CAT);
    
07.05.2018 / 10:10