我有以下数组,其ID为索引,有些则作为值。最终目标是在另一个数组中获得唯一ID的总数。
Array ( [0] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 25 ) ) [1] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 24 ) ) [2] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 23 ) ) [3] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 23 ) ) [4] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 21 ) ) [5] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 21 ) ) [6] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 20 ) ) [7] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 20 ) ) )
我想要下面的结果。
Array ( [0] => Array ( [0] => Team Object ( [id] => 1 [countStat] => 48 ) ) [1] => Array ( [0] => Team Object ( [id] => 2 [countStat] => 44 ) ) [3] => Array ( [0] => Team Object ( [id] => 3 [countStat] => 44 ) ) [4] => Array ( [0] => Team Object ( [id] => 5 [countStat] => 41 ) ) )
我花了几个小时来处理它,但无法解决。有人可以帮忙吗?
谢谢。
答案 0 :(得分:0)
好像您想对队对象的countStats求和,以获得类似的ID。 我创建了一个类似的数据结构,将其循环形成一个临时数组,该数组使用id作为键,并带有关联的金额(总和-我的是金额,您的是countStats)。 然后将它们相加并重新创建所需的输出。
<?php
class Team
{
public $id;
public $amount;
public function __construct($id, $amount)
{
$this->id = $id;
$this->amount = $amount;
}
}
$input =
[
[new Team(1, 3)],
[new Team(1, 4)],
[new Team(2, 5)],
[new Team(2, 7)]
];
foreach($input as $subarray)
$amounts[$subarray[0]->id][]=$subarray[0]->amount;
print_r($amounts);
foreach($amounts as $k => $v)
$result[] = [new Team($k, array_sum($v))];
print_r($result);
输出:
Array
(
[1] => Array
(
[0] => 3
[1] => 4
)
[2] => Array
(
[0] => 5
[1] => 7
)
)
Array
(
[0] => Array
(
[0] => Team Object
(
[id] => 1
[amount] => 7
)
)
[1] => Array
(
[0] => Team Object
(
[id] => 2
[amount] => 12
)
)
)