I am trying to write a recursive function that drills back to the root category of a nest of unknown depth.
[TABLE]
cat_id | cat_name | cat_parent | cat_slug
//each category with a cat_parent of 0 is a root category
[/TABLE]
Example SQL result:
Array
(
[0] => Array
(
[cat_id] => 17
[cat_name] => another-test-category
[cat_parent] => 16
[cat_slug] => Another test category
)
)
Function:
function breadcrumb($cat_id){
$cat_nest =
SELECT *
FROM table
WHERE cat_id = '$cat_id'
//returns 1 row;
$cat_array[$cat_id] = $cat_nest[0];
if($cat_nest[0]['cat_parent'] != 0){
$cat_array[] = breadcrumb($cat_nest[0]['cat_parent']);
}
return $cat_array;
}
It is outputting:
Array
(
[17] => Array
(
[cat_id] => 17
[cat_name] => test.example.1
[cat_parent] => 16
[cat_slug] => Test Example 1
)
[18] => Array
(
[16] => Array
(
[cat_id] => 16
[cat_name] => test.example.2
[cat_parent] => 15
[cat_slug] => Test Example 2
)
[17] => Array
(
[15] => Array
(
[cat_id] => 15
[cat_name] => test.example.3
[cat_parent] => 6
[cat_slug] => Test Example 3
)
[16] => Array
(
[6] => Array
(
[cat_id] => 6
[cat_name] => test.example.4
[cat_parent] => 2
[cat_slug] => Test Example 4
)
[7] => Array
(
[2] => Array
(
[cat_id] => 2
[cat_name] => test.example.5
[cat_parent] => 0
[cat_slug] => Test Example 5
)
)
)
)
)
)
Desired output:
Array
(
[17] => Array
(
[cat_id] => 17
[cat_name] => test.example.1
[cat_parent] => 16
[cat_slug] => Test Example 1
)
[16] => Array
(
[cat_id] => 16
[cat_name] => test.example.2
[cat_parent] => 15
[cat_slug] => Test Example 2
)
[15] => Array
(
[cat_id] => 15
[cat_name] => test.example.3
[cat_parent] => 6
[cat_slug] => Test Example 3
)
[6] => Array
(
[cat_id] => 6
[cat_name] => test.example.4
[cat_parent] => 2
[cat_slug] => Test Example 4
)
[2] => Array
(
[cat_id] => 2
[cat_name] => test.example.5
[cat_parent] => 0
[cat_slug] => Test Example 5
)
)