[英]Sum of same id in Array of object using php
I want to add given_points from both array of object and show in single array of object with the help of student_id bcoz in both array of object student_id is unique.我想从两个对象数组中添加 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;
since this is an array of stdClass , use -> instead of brackets ['']
由于这是一个 stdClass 数组,请使用->代替方括号['']
There is another way : (PHP >= 5.5)还有另一种方式: (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);
You can try something like above code.您可以尝试类似上面的代码。 Basically since the student_id is the unique identifier of your table and you want your logic implemented based on this then make it your new array key field.
基本上,因为 student_id 是表的唯一标识符,并且您希望基于此实现逻辑,然后将其设为新的数组键字段。
The above code will work as many records as you have and the outputted array will look like:上面的代码将处理尽可能多的记录,输出的数组将如下所示:
Array
(
[91] => 16
[92] => 8
[93] => 8
)
2 users with id 91 added, and the rest were unique users in separate array fields.添加了 2 个 id 为 91 的用户,其余是单独数组字段中的唯一用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.