我有以下数组:
Array
(
[0] => Array
(
[year_col] => 2016
[week_col] => 21
[total] => 1
)
[1] => Array
(
[year_col] => 2016
[week_col] => 22
[total] => 2
)
[2] => Array
(
[year_col] => 2016
[week_col] => 22
[total] => 2
)
[3] => Array
(
[year_col] => 2016
[week_col] => 22
[total] => 3
)
[4] => Array
(
[year_col] => 2016
[week_col] => 23
[total] => 2
)
)
我需要为每个total
获得week_col
的总和。在这种情况下,我想得到:
21 => 1, 22 => 7, 23 => 2
我试试:
$sum = 0;
foreach($array as $draw){
$a_filter_draws[$draw['week_col']] = array(
'total_a' => $sum+=$draw['total']
);
}
你能帮帮我吗?它没有返回好的金额。 Thx提前和抱歉我的英语
答案 0 :(得分:1)
试试这个:
<?php
$arrSum = array();
foreach($array as $draw){
if(isset($arrSum[$draw['week_col']])) {
$arrSum[$draw['week_col']] += $draw['total'];
} else {
$arrSum[$draw['week_col']] = $draw['total'];
}
}
?>
答案 1 :(得分:1)
$a_filter_draws = array();
foreach($array as $draw){
if (!isset($a_filter_draws[$draw['week_col']])) {
$a_filter_draws[$draw['week_col']] = 0;
}
$a_filter_draws[$draw['week_col']] += $draw['total'];
}
答案 2 :(得分:0)
<?php
$arr=Array
(Array
(
"year_col" => 2016,
"week_col" => 21,
"total" => 1
)
,Array
(
"year_col" => 2016,
"week_col" => 22,
"total" => 2
)
, Array
(
"year_col" => 2016,
"week_col" => 22,
"total" => 2
)
, Array
(
"year_col" => 2016,
"week_col" => 22,
"total" => 3
)
,Array
(
"year_col" => 2016,
"week_col" => 23,
"total" => 2
)
);
$sum = 0;
$total=0;
foreach($arr as $draw){
$sum+=$draw["week_col"];
$total+=$draw["total"];
}
echo $sum;
echo "<br>";
echo $total;
?>