Multidimensional array (parent and childs)
- by Juan
I have a category system in a MySQL database with parents and childs. The database only stores the id of it''s immediate parent (or 0 if on root). Since the system allows multiple subcategories there are cases of multiple childs.
For example
[98] Storage
[1] External
[3] Pendrives
[4] Portable hhdds
[2] Internal
[5] Sata hhdd
[6] IDE hhdd
[...]
[99] Clothing
The database would be
id parent_id name
1 98 External
2 98 Internal
3 1 Pendrives
4 1 Portable
5 2 Sata
6 2 IDE
98 0 Storage
99 0 Clothing
I also have a products table with a category id and I need to get a list of all the products in the first level of categories.
For example:
Product Category
A 3
B 4
C 5
D 6
E 74
Should return
98: A, B, C, D
99: X, Y, Z...
I'm stuck and I can't think of the logic to retrieve it in that way.
I started by getting the IDs of all the categories that aren't in the first level by:
while ($row = mysql_fetch_assoc($result)) {
if ($row['parent_id'] != 0) {
$level1[$i]['name'] = utf8_encode($row['categories_name']);
$level1[$i]['id'] = $row['categories_id'];
}
$i++;
}
but I'm having a burnout and can't think of a way that would nest them. I thought some kind of while but it's infinite :P
Any ideas please?