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?