php - 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 中尝试查询时,结果是正确的,但是当我在我的网站上尝试时,它总是返回我的方法表中的第一条记录。我找不到它为什么这样做。
感谢帮助。
解决方案
这是因为 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;
}
推荐阅读
- unicode - 从 C++ 中的十六进制数字创建 Unicode
- ssis - 有没有办法编写 DateAdd 和 DatePart SSIS 表达式以始终使用 Getdate() 生成 ThisWeekMonday 的日期?
- python - 如何使用比较其他两列的值创建一个新列?
- python - 如何迭代不同函数的输出?
- azure - 如何在 Azure 负载均衡器入站 NAT 规则上替换目标 VM 和 NIC
- javascript - 创建 NavBar 以执行操作
- validation - 如何仅使用请求在没有插件的情况下验证 AWS 无服务器架构
- python - 如何使用 pymongo 按 13 位 NumberLong 时间字段进行搜索
- r - 如何在 i 中使用 data.table 的 .N?
- django - 如何使用 django-ratelimit 或节流设置多个速率限制,每 10 秒,每 10 分钟,每 1 天?