skip to Main Content

I am having problems summing specific data from an array based on an ID list in another array. Let’s say I have an array like this:

[
    [
        "student_id" => "1",
        "score" => "10",
    ],
    [
        "student_id" => "1",
        "score" => "10",
    ],
    [
        "student_id" => "2",
        "score" => "10",
    ],
    [
        "student_id" => "3",
        "score" => "10",
    ],
]

Then I have a list of students’ IDs in the array

$list = [1, 2, 3];
  • 1 = 20
  • 2 = 10
  • 3 = 10

What I want to achieve is to sum the score based on the student’s ID, then push it to a new array 1 = 20, 2 = 10, 3 = 10. I do this with a nested loop but it’s not working. I have no idea how to do this.

Please give me a hint of how to solve this.

2

Answers


  1. You can use a combination of loops and conditional statements in PHP.

    // Initialize empty array to store the sums
    $sums = [];
    
    // Iterate over the original array
    foreach ($array as $item) {
        $studentID = $item["student_id"];
        $score = (int)$item["score"]; // Convert score to integer
    
        // Check if the student ID is in list
        if (in_array($studentID, $list)) {
            // If the student ID already exists in the sums array, add the score
            if (isset($sums[$studentID])) {
                $sums[$studentID] += $score;
            } 
            // If the student ID doesn't exist in the sums array, 
            // initialize it with the score
            else {
                $sums[$studentID] = $score;
            }
        }
    }
    
    // Print the sums
    print_r($sums);
    
    Login or Signup to reply.
  2. // assuming your first array is $data.
    $result = collect($data)
    ->whereIn('student_id', $list)
    ->groupBy('student_id')
    ->map(function ($group) {
        return $group->sum('score');
    })
    ->toArray();
    
    print_r($result);
    

    the output will be:

    Array
       (
          [a] => 20
          [b] => 10
          [c] => 10
       )
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search