I use Laravel,
I have table tbl_menu
//In model:
public function child()
{
return $this->hasMany('App\Menu', 'parentID', 'ID');
}
//in controller
public function getCountChild()
{
$menu= Menu::where('ID', 2318)->first();
echo '<br>Input: ' . $menu->id;
$gioihan=20;
$countChild = $this->recursiveCountChild($menu, $gioihan);
echo '<br>countChild : ' . $countChild ;
}
public function recursiveCountChild($parent, $gioihan, $limit = 0)
{
$childs = $parent->child;
$limit += $childs->count();
if ($limit < $gioihan && $childs->count() > 0) {
foreach ($childs as $item) {
echo '<br>'. $item->affID.', ';
//$this->dequyCountChild($item, $gioihan, $limit);
return $this->dequyCountChild($item, $gioihan, $limit);
}
}elseif($limit>=$gioihan){
echo "<br>Done: ".$limit;
return $limit;
}
return $limit;
}
And Result:
bad result
I want to get $limit but can not.
it seems, they only run on the left and don't check on the right.
help me. Thanks
My Answer:
To stop a recursive function in PHP (Laravel), you can add a condition to check if the limit has been reached before making the recursive call. Here's an updated version of your code:
php
public function recursiveCountChild($parent, $gioihan, $limit = 0)
{
$childs = $parent->child;
$limit += $childs->count();
if ($limit < $gioihan && $childs->count() > 0) {
foreach ($childs as $item) {
echo '
'. $item->affID.', ';
$limit = $this->recursiveCountChild($item, $gioihan, $limit);
if ($limit >= $gioihan) {
break; // Stop the loop if the limit has been reached
}
}
}
if ($limit >= $gioihan) {
echo "
Done: " . $limit;
}
return $limit;
}
In this updated code, I added a condition to break out of the loop if the limit has been reached. This should help stop the recursive function from running indefinitely and give you the correct result.
Rate this post
4 of 5 based on 2835 votesComments