繁体   English   中英

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

[英]Sum of same id in Array of object using php

我想从两个对象数组中添加 given_points 并在 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
        )

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

}

echo $sum //prints sum
$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'));
$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
)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM