PHP如何从一个数组中根据另一个数组中的id列表获取特定数据

zpjtge22  于 2023-06-28  发布在  PHP
关注(0)|答案(3)|浏览(177)

我在根据一个数组中的ID列表对另一个数组中的特定数据求和时遇到问题。假设我有一个这样的数组:

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

然后我在数组中有一个学生ID列表

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

我想实现的是基于学生ID对分数求和,然后将其推送到新数组1 = 20, 2 = 10, 3 = 10。我用一个嵌套的循环来做这件事,但它不起作用。我不知道该怎么做。
请给予我一个解决这个问题的提示。

ddarikpa

ddarikpa1#

// 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);

输出将是:

Array
   (
      [a] => 20
      [b] => 10
      [c] => 10
   )
mwg9r5ms

mwg9r5ms2#

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

o0lyfsai3#

$scores = [];
foreach ($data as $student) {
    if (in_array($student['student_id'], $list)) {
        if (!isset($scores[$student['student_id']])) {
            $scores[$student['student_id']] = $student['score'];
        } else {
            $scores[$student['student_id']] += $student['score'];
          }
    
    }
}
print_r($scores);

相关问题