我有一个数组,我从数据库
获取*
Array
(
[0] => Array
(
[year] => "2016"
[numb] => 1
)
[1] => Array
(
[year] => "2016"
[numb] => 3
)
[2] => Array
(
[year] => "2017"
[numb] => 3
)
[3] => Array
(
[year] => "2016"
[numb] => 1
)
[4] => Array
(
[year] => "2018"
[numb] => 2
)
)
*
我想结果数组将是这样的
Array
(
[2016] => 5
[2017] => 8
[2018] => 10
)
这意味着:2016 = 1 + 3 + 1 = 5,2017 =(year2016)+ 3,2018 =(year2016)+(year2017)+2。 但2016年并不总是第一年,这取决于数据库
答案 0 :(得分:4)
第一种方法:使用数据库查询(更好的推荐方式)
SELECT DISTINCT y1.year,
(SELECT sum(y2.numb) FROM nums y2 WHERE y2.year <= y1.year) AS numb_total
FROM nums y1
小提琴:http://sqlfiddle.com/#!9/0c6ec5/12
第二种方法:使用PHP方法
// create a container for the new array
$newArray = [];
// get the unique years from array
$years = array_unique(array_column($array, "year"));
// loop them
foreach($years as $year){
// filter the array to match the years less or equal of the current year
$year_filtered = array_filter($array, function($d)use($year){ return intval($d["year"]) <= intval($year);});
// sum the numbers
$total = array_sum(array_column($year_filtered, "numb"));
// place the values in the new array
$newArray[$year] = $total;
}
// echo the output (for debugging purposes)
print_r($newArray);
答案 1 :(得分:2)
$MyNewArray = array();
foreach($YourArray as $Row){
$MyNewArray[$Row->year] = $MyNewArray[$Row->year]+$Row->numb;
}
print_r($MyNewArray);
答案 2 :(得分:0)
我创建了一个新的数组,其中键作为年份,值为麻木 然后按键(年份)对数组进行排序 然后我将值汇总到另一个循环中。
可能有一种更简单的方法,但这是我能想到的。
// create new array with year as key and numb as value
$res =array();
Foreach($arr as $val){
If(!isset($res[$val["year"]])) $res[$val["year"]] =0;
$res[$val["year"]] += $val["numb"];
}
ksort($res); // sort the array on keys to make earliest year first
$newarr= array();
$sum =0;
foreach($res as $key => $val){
$newarr[$key] = $val+$sum; // new array with summed values from previous year(s)
$sum +=$val;
}
Var_dump($newarr);
答案 3 :(得分:-1)
$dbResult = array(array('year' => '2016', 'numb' => 1),
array('year' => '2016', 'numb' => 3),
array('year' => '2017', 'numb' => 3),
array('year' => '2016', 'numb' => 1),
array('year' => '2018', 'numb' => 2));
$result = array();
foreach ($dbResult as $data) {
$result[$data['year']] = (isset($result[$data['year']])) ? $result[$data['year']] : 0;
$result[$data['year']] = $result[$data['year']] + $data['numb'] ;
}
echo '<pre>';print_r($result);