在PHP中如何使用递归函数,如何检查它是否是最后一次迭代?

问题描述 投票:0回答:1

我已启动并运行此递归功能:

function my_function($a, $b, $level=0){
    if( /* we are at the last recursion */ ){
        do something extra special;
    }
    $items = get_some_items($a, $b);
    foreach($items as $item){
        if( /* $item has something special */ ){
            my_function($a, $item, $level++);
        }
    }

}

有了这个,我可以知道哪个迭代是第一次运行。我也可以在任何级别上运行nth

我的问题:我想在最后一次跑步中做一些特别的事情。甚至有办法巧妙地实现这一目标吗?

php recursion
1个回答
0
投票

您可以在末尾添加一个新参数,该参数仅在您所使用的项目号与项目总数相同时才返回true。与此类似吗?

function my_function($a, $b, $level=0,$isLast=false){
    if($isLast){
        // Do something special on last item
    }
    $items = get_some_items($a, $b);    
    $total = count($items);
    $c=0;
    foreach($items as $item){
        $c++;
        my_function($a, $item, $level++,($c==$total));
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.