Php 如何汇总数组中重复项的值?
对不起我的英语 你好,我解决不了这个问题,请帮忙。有一个数组:Php 如何汇总数组中重复项的值?,php,arrays,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(
(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
)
)
如果玩家id在数组中没有唯一的数字,则将其count\u goals增加1。您基本上想要分组和求和:
$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);
我假设你想为每个球员的目标求和?:)@罗伯特(你理解得对)@Alex结果块不应该显示进球总数吗?现在两个代码块显示相同的数组?我添加了一个答案,但我不确定您的意思:
如果玩家id在数组中没有唯一的数字,那么将其count\u goals增加1。
设置count\u goals时?我的猜测是,只是想用输入的数字来增加它?