php 如何在 Laravel Eloquent Collection 的 each 方法中使用 break 或 continue?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29725880/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:32:32  来源:igfitidea点击:

How to use break or continue with Laravel Eloquent Collection's each method?

phplaravelcollectionseloquentlaravel-5

提问by Nasif Md. Tanjim

How to use break or continue with Laravel Eloquent Collection's each method. My code is this:

如何在 Laravel Eloquent Collection 的 each 方法中使用 break 或 continue。我的代码是这样的:

$objectives->each(function($objective) {
        Collection::make($objective)->each(function($action) {
            Collection::make($action)->each(function($success_indicator) {
                Collection::make($success_indicator)->each(function($success_indicator) {
                    echo 'hi';
                    continue;
                });
            });
        });
    });

回答by vijaykumar

We can return true/falsetruefor continue, falsefor break

我们可以返回真/假truecontinuefalsebreak

Continue:

继续:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return true;
            }
            echo $item;
});

Output:1 3 4

输出:1 3 4

Break:

休息:

collect([1,2,3,4])->each(function ($item){
            if ($item === 2) {
                return false;
            }
            echo $item;
});

Output:1

输出:1

回答by Joseph Silber

To continue, just returnout of the inner function. To break, well..

To continue,刚出return内部函数。为了break,嗯..

If you're using Laravel 5.1+, you can return falseto break the loop:

如果你使用的是 Laravel 5.1+,你可以返回false来打破循环:

$objectives->each(function($objective) {
    collect($objective)->each(function($action) {
        collect($action)->each(function($success_indicator) {
            collect($success_indicator)->each(function($success_indicator) {
                if ($condition) return false;
            });
        });
    });
});

For older version of Laravel, use a regular foreachloop:

对于旧版本的 Laravel,请使用常规foreach循环:

$objectives->each(function($objective) {
    foreach ($objective as $action) {
        foreach ($action as $success_indicators) {
            foreach ($success_indicators as $success_indicator) {
                echo 'hi';
                break;
            }
        }
    }
});