1

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.

2 Answers 2

4
$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'];
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If you correct the for loop (it's a foreach loop) and adhere to some coding standards you'll get my vote.
1

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.

2 Comments

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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.