我有一个数组输出是这样的:
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => CROTCH SNIFFER
[2] => TEAM #1 )
[prizeTotal] => 20 )
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => CROTCH SNIFFER )
[prizeTotal] => 60 )
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => TEAM #1 )
[prizeTotal] => 30 )
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => TEAM #2
[2] => SCREW-NUT-BOLT )
[prizeTotal] => 90 )
据说有什么可以分组和总结? 1.对于每个获胜者阵列,奖项总数低于团队名称。该奖金总额应该是其上方每个teamName的值。
实施例
Array ( [winners] =>
Array ( [0] => Gold Member
[1] => CROTCH SNIFFER
[2] => TEAM #1 )
[prizeTotal] => 20 )
Gold Member should have 20
CROTCH SNIFFER should have 20
TEAM #1 should have 20 AND
Array ( [winners] =>
Array ( [0] => TEAM #1
[1] => CROTCH SNIFFER )
[prizeTotal] => 60 )
TEAM #1 should have 60
CROTCH SNIFFER sould have 60....etc....
然后我想按团队名称和总和分组,以便我可以显示......
CROTCH SNIFFER = 80 金牌会员= 50 团队#1 = 200 团队#2 = 90。
提前致谢...
答案 0 :(得分:1)
假设您可以将所有数组收集到一个,即:
$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
...
答案 1 :(得分:0)
您需要创建一个新数组来保存结果,然后对于每个现有数组,检查您是否已经为该团队处理了一个
如果有,则只需将prizeTotal添加到存储在该阵容的新阵列条目中的prizeTotal。
如果没有,只需将团队的条目添加到新阵列。
答案 2 :(得分:0)
我创建了一个模仿mysql SUM()
和GROUP BY
的函数。我希望它能满足您的需求:
$in_a = array(
array("a" => 0,"b"=>0,"s"=> 1),
array("a" => 0,"b"=>0,"s"=> 2),
array("a" => 1,"b"=>1,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>0,"s"=> 1),
array("a" => 0,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>1,"s"=> 1),
array("a" => 1,"b"=>0,"s"=> 1),
);//input array exaple
$group_by_a = array("a","b");//input array will be grouped by these
$sum_a = array("s"); //'s' values of input will be summed
$out_a = array(); //this is the output array
foreach($in_a as $in_i => $in)
{
$add = false;
foreach($out_a as $out_i => $out)
{
$add = true;
foreach($group_by_a as $group_by)
if($in[$group_by] != $out[$group_by])
{
$add = false;
break;
}
if($add)
{
foreach($sum_a as $sum)
$out_a[$out_i][$sum] += $in[$sum];
break;
}
}
if(!$add)
{
foreach($group_by_a as $group_by)
$out_a[$in_i][$group_by] = $in[$group_by];
foreach($sum_a as $sum)
$out_a[$in_i][$sum] = $in[$sum];
}
}
结果:
Array
(
[0] => Array
(
[a] => 0
[b] => 0
[s] => 3
)
[2] => Array
(
[a] => 1
[b] => 1
[s] => 2
)
[3] => Array
(
[a] => 0
[b] => 1
[s] => 3
)
[5] => Array
(
[a] => 1
[b] => 0
[s] => 2
)
)