【问题标题】:Looping through array and totalling values循环遍历数组和总计值
【发布时间】:2010-09-17 17:07:02
【问题描述】:

如果有人愿意提供帮助,我需要一点帮助。

我有一个包含值的数组,我想循环遍历它,如果任何“user_id 值”相同,则计算重复用户 ID 的“max_score”值。

大批 ( [0] => 数组 ( [user_id] => 2 [max_score] => 10081 ) [1] => 数组 ( [user_id] => 1 [max_score] => 8774 ) [2] => 数组 ( [user_id] => 2 [max_score] => 5477 ) [3] => 数组 ( [user_id] => 3 [max_score] => 5267 ) [4] => 数组 ( [user_id] => 1 [max_score] => 5010 ) )

有谁知道如何做到这一点?

非常感谢。

【问题讨论】:

    标签: php arrays loops


    【解决方案1】:
    $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'];
       }
    }
    

    【讨论】:

    • 如果你更正了 for 循环(它是一个 foreach 循环)并遵守一些编码标准,你会得到我的投票。
    【解决方案2】:

    您需要以用户 ID 作为键的第二个数组。你可以这样做:

    $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'];
    }
    

    第三行会阻止php抛出通知。

    【讨论】:

    • 您可以通过添加“if (!isset($scoresums[$user_score['user_id']])) $scoresums[$user_score['user_id']] = 0;”行来解决这个问题在循环的第一行。
    • 哇 - 你们真是太棒了,工作出色,谢谢。现在我有了总分,是否可以按分数降序对特定键的值进行排序?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 2013-03-25
    • 2014-06-04
    • 1970-01-01
    相关资源
    最近更新 更多