【发布时间】:2021-12-10 03:23:43
【问题描述】:
array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
var_export($response) 是一个类似上面的数组。对于$response 数组中的每个courseId,当$response 数组中的courseId 也存在student_learning 表时,我想找到points 的sum。之后,我想将这个点的总和($points)添加到$response 数组中,作为对应courseId 的新项。在这里,问题是,$points 的每个值都作为新项目添加到 $response 数组的每个数据集中,但我希望它被添加到其各自的 $response 数组中 courseId 仅。我该怎么做?
foreach ($response as $key ) {
$points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$key['courseId'])->sum('points');
$res = array_map(function($e) use($points,$percent) {
$e['points'] = $points;
return $e; }, $response);
dump($res);
}
dump($res) 给出如下输出
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 12
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 12
]
]
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 3
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
]
foreach 之外的dump($res) 给出如下输出
array:2 [
0 => array:8 [
"courseId" => 14
"tutorName" => "admin"
"points" => 3
]
1 => array:8 [
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
]
预期/要求的输出:
[
"courseId" => 14
"tutorName" => "admin"
"points" => 12
]
[
"courseId" => 15
"tutorName" => "me"
"points" => 3
]
【问题讨论】:
-
所以你需要为每个数组添加点对吗?
-
@ManojKiranAppathurai 是的。请查看我的预期输出。这就是我想要的
-
你能分享这两个表结构吗
-
@ManojKiranAppathurai 我认为答案无论如何都不会连接到表结构
标签: php arrays laravel eloquent laravel-8