Organize Listing by mysql data parent item in php

Asked

Viewed 46 times

1

I have a list 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>

Data is rescued from a Mysql table with 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?

  • You want a code that creates this list?

1 answer

0

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

Below follows my code that shows a menu the same way you want. You have to remove what doesn’t matter.

To point out 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']);
            }
        }
        }
    }
}

Call from the main programme :

menuTree(-1,0,$CAT);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.