array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
)
var_export($response)是一個像上面那樣的陣列。對于每一個courseId在在$response陣,我想找到sum的points時候courseId中$response陣列存在student_learning也表。之后,我想將這個總點數($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
]
]
dump($res)在外面foreach給出如下輸出
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
]
uj5u.com熱心網友回復:
您可以在使用 foreach 回圈時添加新的陣列鍵
$response = array (
0 =>
array (
'courseId' => 14,
'tutorName' => 'admin',
),
1 =>
array (
'courseId' => 15,
'tutorName' => 'merl',
),
);
$newResponse = [];
foreach($response as $eachResponse){
$points=DB::table('student_learning')->groupBy('courseId')->where('courseId',$eachResponse['courseId'])->sum('points');
$eachResponse['points'] = $points;
$newResponse[] = $eachResponse;
}
dd($newResponse);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334760.html
上一篇:在字串上呼叫成員函式addEagerConstraints()-Laravel8
下一篇:PHP二叉樹遞回遍歷無限回圈問題
