tags:

views:

64

answers:

2

Hello,

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.

+1  A: 

Hi, 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.

Thomas
-1 this will throw notices.
nikic
you can fix that by adding the line "if (!isset($scoresums[$user_score['user_id']])) $scoresums[$user_score['user_id']] = 0;" in the first row of the loop.
Thomas
Wow - you guys are absolutely amazing, works brilliantly, thanks. Now that I have my totalled score, is there anyway to order the value of a particular key by score descending?
Sibbels
+4  A: 
$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'];
   }
}
brian_d
If you correct the for loop (it's a foreach loop) and adhere to some coding standards you'll get my vote.
nikic