Laravel - 我可以根据该数组现有的 `id` 值向该数组添加新项目吗?

Laravel - Can i add new item to an array based on the `id` value existing that array?

array (
   0 =>
    array (
    'courseId' => 14,
    'tutorName' => 'admin',
    ),
   1 =>
    array (
    'courseId' => 15,
    'tutorName' => 'merl',
    ),
 )

var_export($response) 就是和上面一样的数组。对于 $response 数组中的每个 courseId,当 $response 数组中的 courseId 存在时,我想找到 pointssum student_learningtable也。之后,我想将这个点数之和($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
  ]
]

Expected/Required 输出:

  [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 12
  ]
  [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 3
  ]

您可以在使用 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);