基于CodeIgniter构建支持任意层级的分类面包屑动态函数
Hey there! Let's revamp your code to support any depth of subcategories instead of being limited to three levels. The core fix here is replacing your hardcoded parent checks with a recursive function that can traverse up the category tree until it hits a root parent (parent = 0).
Revised Controller Code
public function index() { $dbdata['table'] = 'categories'; $dbdata['select'] = array('id', 'parent', 'name'); $dbdata['where'] = array('type' => 'post'); $records = $this->ot->get_records($dbdata); $category_breadcrumbs = array(); foreach ($records as $record) { // Use our recursive function to build the full breadcrumb trail $breadcrumb_parts = $this->get_breadcrumb_recursive($record['id'], $records); // Reverse the parts to get root-to-current order, then join with " > " $category_breadcrumbs[] = implode(' > ', array_reverse($breadcrumb_parts)); } echo ' <pre>'; print_r($records); echo '<hr>'; print_r($category_breadcrumbs); echo '</pre>'; } /** * Recursive function to collect all parent category names up to the root * @param int $current_id ID of the category to start from * @param array $all_records Full list of category records * @return array List of category names from current up to root */ protected function get_breadcrumb_recursive($current_id, $all_records) { // Find the current category in the records array $key = array_search($current_id, array_column($all_records, 'id')); $current_category = $all_records[$key]; $breadcrumb = array($current_category['name']); // If current category has a parent (and parent isn't 0), recursively get parent's breadcrumb if ($current_category['parent'] != 0) { $parent_breadcrumb = $this->get_breadcrumb_recursive($current_category['parent'], $all_records); // Merge parent's breadcrumb with current category's name $breadcrumb = array_merge($parent_breadcrumb, $breadcrumb); } return $breadcrumb; }
How This Works
- Recursive Function:
get_breadcrumb_recursivestarts with the current category, adds its name to the trail, then checks if it has a parent. If yes, it calls itself with the parent ID to collect that parent's trail, and merges them together. - Root-to-Current Order: After collecting the trail from current category up to root, we use
array_reverseto flip it so it displays asRoot > Parent > Child > Grandchild. - Flexible Depth: This will work for 1 level, 3 levels, 10 levels—any depth your category tree has.
Example Output (With a 4-Level Category)
If you add a category like id:13, parent:3, name:Category 13, your output will include:
Array ( ... [12] => Category 1 > Category 2 > Category 3 > Category 13 )
This approach keeps your code clean, scalable, and adaptable to any future category depth changes.
内容的提问来源于stack exchange,提问作者Abdul Roshan
相关产品推荐
相关产品推荐

