I have a category tree array fetched from MySQL Table. I want to revert this Category array tree back into Breadcrumb list using PHP.
PHP Category Tree Building Function
function buildTree(array &$elements, $parentId = 0)
{
$branch = array();
foreach ($elements as $element) {
if ($element['parent_category_id'] == $parentId) {
$children = buildTree($elements, $element['category_id']);
if ($children) {
$element['children'] = $children;
}
$branch[$element['category_id']] = $element;
unset($elements[$element['category_id']]);
}
}
return $branch;
}
Result Array
[48] => Array
(
[category_id] => 48
[category_name] => Cat 1
[parent_category_id] => 0
[children] => Array
(
[957] => Array
(
[category_id] => 957
[category_name] => Cat 2
[parent_category_id] => 48
[children] => Array
(
[1528] => Array
(
[category_id] => 1528
[category_name] => Cat 3
[parent_category_id] => 957
)
[1890] => Array
(
[category_id] => 1890
[category_name] => Cat 4
[parent_category_id] => 957
)
[1570] => Array
(
[category_id] => 1570
[category_name] => Cat 5
[parent_category_id] => 957
)
[958] => Array
(
[category_id] => 958
[category_name] => Cat 6
[parent_category_id] => 957
)
)
)
Now I want to convert this array tree back into Breadcrumb List using PHP, for example
"Cat 1 > Cat 2 > Cat 3"
"Cat 1 > Cat 2 > Cat 4"
"Cat 1 > Cat 2 > Cat 5"
"Cat 1 > Cat 2 > Cat 6"
Any help would be much appreciated.
Screenshot
hope it can be helpful
The key concept is converting your tree into a flat array where each category is indexed by it's ID. From that flat structure, you can walk up the hierarchy until you reach the root for each category, creating an array of the levels. I've created a helper class to encapsulate the basic functionality you might want for breadcrumbs. The recursion happens in the
_unwindTree
method. The_buildBreadcrumbs
method calls this function and uses the resulting flat array to build the breadcrumb "lines" for each category. These are the two functions to look at to understand how you convert a tree into an array of category paths.There are some public functions that provide access to the breadcrumb data in different ways.