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
How to use break or continue with Laravel Eloquent Collection's each method?
提问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/falsetrue
for continue
, false
for break
我们可以返回真/假true
的continue
,false
对break
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 return
out of the inner function. To break
, well..
To continue
,刚出return
内部函数。为了break
,嗯..
If you're using Laravel 5.1+, you can return false
to 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 foreach
loop:
对于旧版本的 Laravel,请使用常规foreach
循环:
$objectives->each(function($objective) {
foreach ($objective as $action) {
foreach ($action as $success_indicators) {
foreach ($success_indicators as $success_indicator) {
echo 'hi';
break;
}
}
}
});