簡體   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