I have written a loop which first checks for whether, in this case, a Category has any Subcategories based on a field in the database called 'category_id' in the subcategory table.
What I would like it to do here on is recursively check Subcategories to see if there are any Subcategories with the 'parent_id' set to the respective id. What the check needs to do is add to an array (see code snippet below for a better explanation).
Firstly to illustrate an example structure:
Main Category
- Sub category level 1 (identified by 'category_id' matching 'id' of Main Category)
- - Sub category level 2 (identified by 'parent_id' matching 'id' of Sub category level 1
- - - Sub category level 3 (identified by 'parent_id' matching 'id' of Sub category level 2
This is intended to continue indefinitely. Here is an example of a non-recursive function which performs the task correctly:
$final = [];
foreach($values as $k => $v) {
$check = collect(Subcategory::where('category_id', $v['id'])->get());
$v['subcategory'] = 0;
$final[] = $v;
if (count($check) > 0) {
foreach($check as $c) {
$val = $c->toArray();
$val['name'] = '- '.$val['name'];
$val['subcategory'] = 1;
$final[] = $val;
/* recursive here onward */
$check2 = collect(Subcategory::where('parent_id', $c['id'])->get());
if (count($check2) > 0) {
foreach($check2 as $c) {
$val = $c->toArray();
$val['name'] = '- - '.$val['name'];
$final[] = $val;
$check3 = collect(Subcategory::where('parent_id', $c['id'])->get());
if (count($check3) > 0) {
foreach($check3 as $c) {
$val = $c->toArray();
$val['name'] = '- - - '.$val['name'];
$final[] = $val;
}
}
}
}
}
}
}
I can't work out how to make this recursive despite seeing the repeated sections. Could anyone suggest a recursive function that would consistently perform what is below "recursive here onward" in the code snippet until the check returns 0?
foreach(){}in a function and call this functions insideif(count($check)>0) { }with $check as param.