使用php在对象数组中的相同ID的总和

时间:2019-03-21 12:37:29

标签: php

我想从两个对象数组中添加给定的点,并在student_id bcoz的帮助下在单个对象数组中显示,在两个对象Student_id数组中都是唯一的。

Array
(
    [0] => stdClass Object
        (
            [student_id] => 91
            [given_points] => 8
            [bonus_points] => 2
        )

    [1] => stdClass Object
        (
            [student_id] => 91
            [given_points] => 6
            [bonus_points] => 1
        )

)
Array
(
    [0] => stdClass Object
        (
            [student_id] => 95
            [given_points] => 9
            [bonus_points] => 1
        )

    [1] => stdClass Object
        (
            [student_id] => 95
            [given_points] => 9
            [bonus_points] => 1
        )

)

3 个答案:

答案 0 :(得分:0)

$sum = 0;
foreach($array as $key => $value)
{
 sum+=$array[$key]['given_points'];

}

echo $sum //prints sum

答案 1 :(得分:0)

$sum_points = 0;
$sum_student_id=0;
foreach($array as $key=>$value){
  if(isset($value->given_points))
     $sum_points += $value->given_points;
  if(isset($value->student_id))
     $sum_student_id += $value->student_id;
}
echo $sum_points;
echo $sum_student_id;
  

因为这是一个stdClass数组,所以请使用-> 而不是方括号     ['']

还有另一种方法:(PHP> = 5.5)

$sum_points = array_sum(array_column($array, 'given_points'));
$sum_student_ids = array_sum(array_column($array, 'student_id'));

答案 2 :(得分:0)

$array = [
    0 => ['student_id' => 91,
        'given_points' => 8,
        'bonus_points' => 2
    ],
    1 => ['student_id' => 91,
        'given_points' => 8,
        'bonus_points' => 2
    ],
    2 => ['student_id' => 92,
        'given_points' => 8,
        'bonus_points' => 2
    ],
    3 => ['student_id' => 93,
        'given_points' => 8,
        'bonus_points' => 2
    ]
];


foreach ($array as $row) {
    if (isset($newArray[$row['student_id']])) {
        $newArray[$row['student_id']] = $newArray[$row['student_id']] + $row['given_points'];
    } else {
        $newArray[$row['student_id']] = $row['given_points'];
    }
}

print_r($newArray);

您可以尝试类似上面的代码。基本上,由于student_id是表的唯一标识符,因此您希望基于此表实现逻辑,然后使其成为新的数组键字段。

上面的代码将使用尽可能多的记录,并且输出的数组将如下所示:

Array
(
    [91] => 16
    [92] => 8
    [93] => 8
)

添加了ID为91的2个用户,其余的是在单独的数组字段中的唯一用户。