Hi All, sometimes you’re working with eCommerce site and you want to get all subcategories including all level of childs like,
1 2 3 4 5 6 7 8 | category sub-category1 sub-category2 sub-sub-category1 sub-sub-category2 sub-category3 |
So, Here I am going to explain how to get all child categories in PHP. In the following function, I have recursively called function to get all level child categories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <?php function getCategoryTreeFromParent($parent_id = 0,$category= array()) { $categories = mysql_query("SELECT * FROM categories WHERE parent_id = $parent_id"); foreach ($categories as $category) { // again recursively call this function until all levels of category returns $sub_category['sub_categories'] = getCategoryTreeForParentId($category['id']); if($sub_category['sub_categories']!=''){ array_push($categories,$category['category_id'],$sub_category['sub_categories']); }else{ array_push($categories,$category['category_id']); } } $category_arr = array(); // to flat multilevel array into single (one) level array_walk_recursive($categories, function($arr) use (&$category_arr) { $category_arr[] = $arr; }); return $category_arr; return $category_arr; } ?> |
That’s it. You can use above function where you require.
Suggested Read:
To create Zoho leads using PHP
To convert PHP array into Javascript array
To grab content from nested tags in PHP
Hope this helps someone else out.As always, thanks for reading. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.
Comments (2)