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

Time:10-24

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

var_export($response) is an array like above. For each courseId in the $response array, i wanted to find sum of points when the courseId in the $response array exists student_learning table also. After that, i wanted to add this sum of points($points) to the $response array as a new item for the corresponding courseId. Here, the issue is that, every values of $points is added as a new item in every datasets of the $response array,but i wanted it to get added to the $response array of it's respective courseId only. How can i do that?

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) gives an output like below

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) outside the foreach gives an output like below

array:2 [
  0 => array:8 [
    "courseId" => 14
    "tutorName" => "admin"
    "points" => 3
  ]
  1 => array:8 [
    "courseId" => 15
    "tutorName" => "me"
    "points" => 3
  ]
]

Expected/Required Output:

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

CodePudding user response:

You can add new array key while looping using 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);
  • Related