3

As part of an eCommerce solution we're working on, the CMS has the option for product categories to have an unlimited number of sub-categories, and each sub-category can have an unlimited number of sub-categories. Basically, there is an unlimited nesting-level for product categories.

The database table schema for the categories looks something like this:

+-------------+-----------------+----------------+
| category_id |      name       |   parent_id    |
+-------------+-----------------+----------------+
|     1       |    Parent 1     |      null      |
|     2       | Child of Parent |        1       |
+-------------+-----------------+----------------+

We want to add in a breadcrumbs navigation for each level of the category navigation, so my question is, what is the best practice for looping through the categories while there is a parent assigned, until it reaches the top level?

Obviously, we can code it in a fixed loop (for example if($child->hasParent()) { echo '1'; if($child->children->hasParent() { } } etc.

How do you iterate through an unknown number of categories until you reach the top-level category (i.e. the category which has no parent_id assigned?

BenM
  • 52,573
  • 26
  • 113
  • 168

2 Answers2

2

Just use the while loop for this.

while($child->hasParent()) {
     echo $child->name();
     $child = $child->Parent();
}
Balanivash
  • 6,709
  • 9
  • 32
  • 48
0

If(parent class==null)

then child class==null

else hasparent class(null)==0

repeat