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
You can use a combination of loops and conditional statements in PHP.
the output will be: