如何总结数组中重复的值?

时间:2017-12-26 12:00:03

标签: php arrays

抱歉我的英文。

您好,我解决不了问题,请帮忙。有一个数组:

array(
    (int) 0 => array(
        'player_id' => '1',
        'count_goals' => (int) 1
    ),
    (int) 1 => array(
        'player_id' => '2',
        'count_goals' => (int) 1
    ),
    (int) 2 => array(
        'player_id' => '1',
        'count_goals' => (int) 1
    )
)

结果应为:

array(
    (int) 0 => array(
        'player_id' => '1',
        'count_goals' => (int) 1
    ),
    (int) 1 => array(
        'player_id' => '2',
        'count_goals' => (int) 1
    ),
    (int) 2 => array(
        'player_id' => '1',
        'count_goals' => (int) 1
    )
)

如果player_id在数组中没有唯一编号,则将count_goals增加1。

1 个答案:

答案 0 :(得分:0)

你基本上想要分组和总结:

$result = [];
foreach ($input as $row) {
    if (!isset($result[$row['player_id']])) {
        $result[$row['player_id']] = 0;
    }
    $result[$row['player_id']] += $result[$row['count_goals']];
}

这将为您提供如下数组:

[
   1 => 2, // player_id => sum of count_goals
   2 => 1,
]

然后,如果需要,您可以将其转换回关联数组。

$finalResult = [];
foreach ($result as $playerId => $sumOfGoals) {
     $finalResult[] = [
         'player_id' => $playerId,
         'count_goals' => $sumOfGoals,
     ];
}

print_r($finalResult);