如何用PHP编程实现无限递归
我有一系列问题。每个问题都可以有孩子,孩子也可以有孩子。我的数据库设置如下:如何用PHP编程实现无限递归,php,recursion,laravel-5.1,Php,Recursion,Laravel 5.1,我有一系列问题。每个问题都可以有孩子,孩子也可以有孩子。我的数据库设置如下: id: incrementing id, question: string, parentId: integer, industryId: integer 因此,基本上,当我保存一个家长级别的问题时,它的家长ID为“0”。如果该问题保存为id=1。然后子项将是parentId=1,依此类推 我需要无限循环遍历products数组以确定是否有更多的子项,但我无法找到一种非手动的方法。这是我的密码: <?php
id: incrementing id, question: string, parentId: integer, industryId: integer
因此,基本上,当我保存一个家长级别的问题时,它的家长ID为“0”。如果该问题保存为id=1。然后子项将是parentId=1,依此类推
我需要无限循环遍历products数组以确定是否有更多的子项,但我无法找到一种非手动的方法。这是我的密码:
<?php
//Does this question have sub questions?
$hasChildren = FALSE;
foreach($questions as $q) {
if($q->parentId === $question->id) {
$hasChildren = TRUE;
}
}
if($hasChildren === TRUE):
$unique = uniqid();
?>
<ul class="sub-list-{{$unique}}">
@foreach($questions as $q)
@if($q->parentId === $question->id)
<li>{{$q->question}}
<?php
//Does this question have sub questions?
$hasChildren = FALSE;
foreach($questions as $q1) {
if($q1->parentId === $q->id) {
$hasChildren = TRUE;
}
}
if($hasChildren === TRUE):
$unique = uniqid();
?>
<ul class="sub-list-{{$unique}}">
@foreach($questions as $q1)
@if($q1->parentId === $q->id)
<li>{{$q1->question}}
</li>
@endif
@endforeach
</ul>
<?php endif; ?>
</li>
@endif
@endforeach
</ul>
<?php endif; ?>
@foreach($q形式的问题)
@如果($q->parentId===$question->id)
- {{$q->问题}
@foreach(问题为$q1)
@如果($q1->parentId===$q->id)
- {{$q1->问题}
@恩迪夫
@endforeach
@恩迪夫
@endforeach
我没有在任何应用程序中使用过laravel 5.1,在一年前我使用过laravel 4.2,我可以建议制作一个类似nav.blade的刀片,如果可能的话,也包括它,不知道它是否可能。我在wordpress/woocommerce中做过类似的事情,但您将如何在这里实现它,不知道。你可以在这里看到我做了类似的事情。递归函数听起来很简单,将子打印移到这个函数中,然后对于每个问题,调用它来打印子项,如果子项有其他子项,则使用当前子项id调用函数来打印其子项或关闭标记。我不使用laravel,但如果你愿意,我可以用基本php编写一个示例代码。我没有在任何应用程序中使用过laravel 5.1,在一年前我使用过laravel 4.2,我可以建议制作一个类似nav.blade的刀片,如果可能的话,我不知道是否可能。我在wordpress/woocommerce中做过类似的事情,但是你将如何在这里实现它,不知道。你可以在这里看到我做了类似的事情。递归函数听起来很简单,将子打印移到这个函数中,然后对于每个问题,调用它来打印子项,如果子项有其他子项,则使用当前子项id调用函数来打印其子项或关闭标记。我不使用laravel,但如果您愿意,我可以用基本php编写示例代码。