我编写了一个循环,首先检查一个类别是否具有基于数据库中名为' category_id'的字段的任何子类别。在子类别表中。
我希望它在这里做的是递归检查子类别,看看是否有任何子类别与' parent_id'设置为相应的ID。检查需要做的是添加一个数组(请参阅下面的代码片段以获得更好的解释)。
首先说明一个示例结构:
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
这是为了无限期地继续下去。以下是正确执行任务的非递归函数的示例:
$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;
}
}
}
}
}
}
}
尽管看到了重复的部分,但我无法弄清楚如何进行这种递归。任何人都可以建议一个递归函数,它将始终如一地执行下面的"递归到这里"在代码片段中,直到检查返回0?
答案 0 :(得分:1)
通常,您希望从递归函数中获得的是使用上一步获取的数据进行新计算,并且您可能还需要您所处的递归级别。
在您的情况下,您需要提供函数的数据是类别ID和递归级别。
所以我建议你尝试类似下面的代码:
function getSubCategories($id, $level) {
$check = collect(Subcategory::where('category_id', $id)->get());
$subCategories = array();
foreach ($check as $c) {
$val = $c->toArray();
$subCategories[] = array(
'id' => $val['id'],
'name' => str_repeat('- ', $level) .$val['name'],
'level' => $level,
'subIds' => getSubCategories($val['id'], ++$level)
);
}
return $subCategories;
}
// Call the function.
$categories = array(
'id' => 1,
'name' => 'name',
'level' => 0,
'subIds' => getSubCategories(1, 1)
);
最后,您可以使用另一个递归函数来打印数据,如下所示:
function printR($category) {
print $category['name'] . $category['level'] . "\n";
foreach ($category['subIds'] as $sub) {
printR($sub);
}
}
printR($categories);