mysql - How to create nested category list from category-strings in PHP
I have a MySQL table "products" that has a column called "category". In this field you find the categorie herarchy for every product as a string. E.g.:
female / dresses / long
female / dresses / short
female / shoes
male / shoes / sneakers / skate
...
I selected all different categories with:
$result = $mysqli->query("SELECT DISTINCT category FROM products ORDER BY category");
Now, I want to be able to print these categories as a nested HTML-list like
- female
- dresses
- long
- short
- shoes
- dresses
- male
- shoes
- sneaker
- skate
- sneaker
- shoes
Any advice would be very much appreciated. Thanks!
EDIT: I get the data from several csv files, so a solution without the need of transforming the categories would be great!
Answer
Solution:
Just construct your tree using the categories as the node's key. For example :
Now,
var_export($categoryTree)
will output :and
displayCategoryTree($categoryTree)
will output :** Edit **
To get the HTML representation of the tree :
and will output :
Answer
Solution:
As others mentioned in comments, you'd better to use
nested tree sets
for this kind of categorization, but since you asked you don't want to change the scheme of your category system and IF and only IF you're not concerned about your run-time overload, you can use this code that I wrote.For populating an array of categories:
You can replace my
foreach
on$rows
with your fetchwhile
loop.For displaying of categories:
Current demonstration: