我需要展平多维数组以形成唯一值及其总和的关联数组。
我的示例数组:
[
[
'winners' => [
'Gold Member',
'CROTCH SNIFFER',
'TEAM #1'
],
'prizeTotal' => 20
],
[
'winners' => [
'TEAM #1',
'CROTCH SNIFFER'
],
'prizeTotal' => 60
],
[
'winners' => [
'Gold Member',
'TEAM #1'
],
'prizeTotal' => 30
],
[
'winners' => [
'TEAM #1',
'TEAM #2',
'SCREW-NUT-BOLT'
],
'prizeTotal' => 90
]
]
请原谅这些名字......这不是我的数据库。
在每个数据集中,prizeTotal
被授予 winners
子数组中的每个值。
如何对获奖者
值进行分组并对它们各自的prizeTotal
值进行求和?
期望的结果:
array (
'Gold Member' => 50,
'CROTCH SNIFFER' => 80,
'TEAM #1' => 200,
'TEAM #2' => 90,
'SCREW-NUT-BOLT' => 90,
)
最佳答案
假设您可以将所有数组收集到一个数组中,即:
$arrays = array($array1,$array2,....,$arrayn);
然后
$grouping = array();
foreach($arrays AS $array)
{
foreach($array['winners'] AS $k=>$v)
{
//check if the array key is a number, will contain a team, and if that
//them is not alreay listed
if(is_numeric($k) && !array_key_exists($v,$grouping))
$grouping[$v] = 0;
//sum the prize to the team's sum
$grouping[$v] += intval($array['winners']['prizeTotal']);
}
}
//the following is just for debugging
print_r($grouping);
这应该会产生类似的结果:
$grouping[TEAM #1] = 200
$grouping[TEAM #2] = 90
$grouping[CROTCH SNIFFER] = 200
...
关于php - 将 3d 数组转换为唯一值的关联数组并对它们的相关值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6298749/