Sibbels
Sibbels

Reputation: 11

Looping through array and totalling values

I require a bit of assistance, if someone would be kind enough to help.

I have an array with values, which I want to loop through, and if any of the 'user_id values' are the same then to total the 'max_score' value of the duplicate user id's.

Array
(
    [0] => Array
        (
            [user_id] => 2
            [max_score] => 10081
        )

    [1] => Array
        (
            [user_id] => 1
            [max_score] => 8774
        )

    [2] => Array
        (
            [user_id] => 2
            [max_score] => 5477
        )

    [3] => Array
        (
            [user_id] => 3
            [max_score] => 5267
        )

    [4] => Array
        (
            [user_id] => 1
            [max_score] => 5010
        )
)

Would anyone know how to accomplish this?

Many thanks.

Upvotes: 1

Views: 199

Answers (2)

brian_d
brian_d

Reputation: 11385

$totals = array();
foreach ($your_array_values as $v) {
   $id = $v['user_id'];
   if (isset($totals[$id])) {
      $totals[$id] += $v['max_score'];
   } else {
      $totals[$id]  = $v['max_score'];
   }
}

Upvotes: 4

Thomas
Thomas

Reputation: 10669

you need a second array with the user ids as key. You can do it like this:

$scoresums = array();
foreach ($yourarray AS $user_score) {
    if (!isset($scoresums[$user_score['user_id']])) $scoresums[$user_score['user_id']] = 0; 
    $scoresums[$user_score['user_id']] += $user_score['max_score'];
}

The third line will prevent php from throwing notices.

Upvotes: 1

Related Questions