如何使用休息或继续使用Laravel Eloquent Collection的每种方法?

时间:2015-04-19 04:43:31

标签: php laravel collections eloquent laravel-5

如何使用休息或继续使用Laravel Eloquent Collection的每种方法。 我的代码是这样的:

$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;
                });
            });
        });
    });

2 个答案:

答案 0 :(得分:22)

continue,只需return内部函数。致break,嗯..

如果您使用的是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;
            });
        });
    });
});

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

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

答案 1 :(得分:22)

我们可以为true返回 true / false continuefalse

返回break

继续

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

<强>输出: 1 3 4

<强>中断:

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

<强>输出: 1