首页 > 解决方案 > Laravel foreach 总是返回第一个数据

问题描述

在这个 foreach 中,我使用一个函数来提取分数,我将从 foreach 获得的值写入函数中。

foreach($surveys AS $s) {
        $surList[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
    }

并且在这个函数中返回与我们在数据库中使用 case-when 得到的分数相对应的消息

 function getSubtitle($id,$score){
    $surveys=DB::table("methodolgy")->where("main_survey",$id)->selectRaw("*, (CASE WHEN ".$score." BETWEEN start AND end THEN message ELSE 'bos' END) AS sonuc")->having("sonuc","!=","'bos'")->orderBy("id","ASC")->first();
    return isset($surveys->message) ? $surveys->message : "Activity Not Found";
}

问题是,当我在 SQL 中尝试查询时,结果是正确的,但是当我在我的网站上尝试时,它总是返回我的方法表中的第一条记录。我找不到它为什么这样做。

感谢帮助。

标签: phpsqllaravel

解决方案


这是因为 foreach 函数总是读取数组中的 aray 和 foreach 数据,它会做一些事情。对于您的情况,它将数据分配给变量。您可以创建一个像 $allData 这样的变量,然后将数组的每个数据附加到它。例如

$surList = [];    
foreach($surveys AS $s) {
        $oneData[$s->cat][] = ["id" => $s->id, "title" => $s->title, "score" => SurveyController::getScore($s->id),"subtitle" => SurveyController::getSubtitle($s->id,SurveyController::getScore($s->id)) ];
        $surList.=$oneData;
    }

推荐阅读