简体   繁体   中英

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.

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 ['']

There is another way : (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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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