Home > database >  how to category list? [PHP accordion]
how to category list? [PHP accordion]

Time:11-28

I need to create unlimited categories, and ı use php mysql.

My database struct.

id name parent_id
1 Electronic 0
2 Laptop 1
3 Desktop 1
4 Car 0
5 Renault 4
6 Megane 5

the look i want to achieve ;

enter image description here

I want to make an accordion menu like this with php but I couldn't find an example, really.

Can you recommend me a method?

CodePudding user response:

The PHP part: Create for example a recursive Function with one parameter. The parameter is the parentId with 0 as default value.

Inside this function do a Query that selects all entrys where the parent_id is the parameter of the function.

Now do a foreach. inside the foreach call this function but give the id (not the parentid) as parameter and add the result of the subquery to the result of the row as a new column.

In this way you get an array with nesting.

Return this array with nesting.

For showing you basicly do the same again. Create an recursive function that just iterates through the given array and inside the foreach it goes into the next level as parameter you give the subarray. And then you echo the html code for the current entry.

For styling use bootstrap.

Thats maybe not the most beautiful way, but the short and easy one.

OT: Keep in mind, that unlimited nesting can be confusing when it has many levels.

What you are looking for is something similar to this: https://stackoverflow.com/a/5726311/10790010

CodePudding user response:

Thank u but my problem is html ( ı think )

my tree algorithm :

function buildTree($elements, $parentId = 0){

$branch = array();

foreach ($elements as $element) {

if ($element->parent_id == $parentId) {

  $children = buildTree($elements, $element->id);

  if ($children) {
    $element->children = $children;
  } else {
    $element->children = array();
  }

  $branch[] = $element;
}

}

return $branch; }

and draw html

function drawElements($items) {

echo "<ul class='test'>"; 

foreach ($items as $item) {

  echo "<li><a class='link' href='#''>{$item->name}</a></li>";

  if (sizeof($item->children) > 0) {
    drawElements($item->children);
  }
}
echo "</ul>"; 

}

but this way I can't separate the html elements and I can't make an accordion menu as I want.

  • Related