首页 > 解决方案 > 如何在方法导致 php 之前停止 foreach 循环迭代?

问题描述

lenght=13我有一个我正在使用的数组()foreach

$games = array(1,2,3,4,5,6,7,8,9,10,11,12,13);
foreach($games as $game_id){
    $this->insertTrainingData($game_id, 'advance', 5);
    $this->insertTrainingData($game_id, 'intermediate', 4);
    $this->insertTrainingData($game_id, 'easy', 3);            
}

上面的 foreach 循环根据某些验证将每个 game_id 传递insertTrainingData()给插入。game_id

insertTrainingData()在插入记录之前验证每个game_id,如果一切顺利,则为特定组 ( advance, intermediate, easy) 存储 game_id 函数。

我面临什么问题?

当 foreach 循环insertTrainingData()在单次迭代中将 game_id 传递给被调用的方法 3 次,然后跳转到下一次迭代然后相同的过程。我正在考虑下一次迭代 foreach 循环在完成上一次迭代作业之前传递 game_id (insertTrainingData())

如果我可以停止 foreach 循环迭代,直到所有函数返回最终结果,然后在下一次迭代中让 foreach 循环,这是否可能。我就是这么想的,不知道是不是我错了。

这是根据验证决定为特定组插入 game_id 的函数。

private function insertTrainingData($game_id, $type, $limit){
    $error = 0;
    $result = true;
    $todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->get();
    if($todayTraining->count() === $limit ){
        $error = 1;
        $result = false;
    }

    $todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->get();

    if($todayExist->count() > 0 || $todayExist->first() !== null){
        $error = 1;
        $result = false;
    }

    $recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->get();
    if($recordInTwoRowDays->count() > 0 ){
        $error = 1;
        $result = false;
    }

    if($error === 0){
        $AddTraining           = new Training;
        $AddTraining->game_id    = $game_id;
        $AddTraining->type       = $type;
        $AddTraining->save();
        $result = true;
    }

    return $result;
}

当我执行上面的脚本时发生了什么?

实际上上面的脚本为advance组添加了 6 行但是你可以看到limit5

有人可以指导我吗,我真的很感激。

太感谢了。

标签: phplaravel

解决方案


您的代码很好,它不应该插入第 6 行,也许您看错了地方,但是,这里是您可以改进的代码:

  1. 当第一个语句为假时,它不会适用于其他 if 语句
  2. 因此它不会调用第二条 SQL 语句
  3. ->count() 比 ->get()->count() 好得多

.

private function insertTrainingData($game_id, $type, $limit) {
    $todayTraining = Training::whereRaw("Date(created_at)=Curdate() and type='".$type."'")->count();
    if ($todayTraining >= $limit ) {
        return false;
    }

    $todayExist = Training::whereRaw("Date(created_at)=Curdate() and game_id=$game_id")->count();
    if ($todayExist > 0) {
        return false;
    }

    $recordInTwoRowDays = Training::whereRaw("created_at >= DATE_ADD(CURDATE(), INTERVAL -1 DAY) and game_id=$game_id and type='".$type."'")->count();
    if ($recordInTwoRowDays > 0 ) {
        return false;
    }

    $addTraining = new Training();
    $addTraining->game_id = $game_id;
    $addTraining->type = $type;
    $addTraining->save();
    return true;
}

推荐阅读