我有一个带有日期时间列和小计列的 2d 数组。 我需要按日期时间值的日期部分对行进行分组,并对每个组中的小计值求和。
示例输入数组:
[
['id' => 81, 'placed' => '2013-09-19 16:32:53', 'sub_total' => 786],
['id' => 80, 'placed' => '2013-09-19 16:32:06', 'sub_total' => 780],
['id' => 79, 'placed' => '2013-09-18 17:06:48', 'sub_total' => 786],
['id' => 78, 'placed' => '2013-09-18 17:05:02', 'sub_total' => 756],
['id' => 77, 'placed' => '2013-09-17 17:02:53', 'sub_total' => 786],
['id' => 76, 'placed' => '2013-09-16 17:02:53', 'sub_total' => 756],
]
期望输出:
[
['placed' => '2013-09-19', 'sub_total' => 1566],
['placed' => '2013-09-18', 'sub_total' => 1542],
['placed' => '2013-09-17', 'sub_total' => 786],
['placed' => '2013-09-16', 'sub_total' => 756],
]
我也测试了这个:http://phpfiddle.org/main/code/rzv-ngp
$newarray = array();
foreach ($array as $value){
$temp = explode(" ", $value['placed']);
$date = $temp[0];
$total = (isset($newarray[$date]['sub_total']) ? $newarray[$date]['sub_total'] + $value['sub_total']: $value['sub_total']);
$newarray[$date] = array('placed' => $date, 'sub_total' => $total);
}
print_r($newarray);
$output=array();
foreach($yourArray as $values)
{
$d=date("Y-m-d",strtotime($values["placed"]));
$output[$d]["sub_total"]+=$values["sub_total"];
}
print_r($output);
输出:
Warning: Undefined array key "2013-09-19" in /in/SO65c on line 17
Warning: Undefined array key "sub_total" in /in/SO65c on line 17
Warning: Undefined array key "2013-09-18" in /in/SO65c on line 17
Warning: Undefined array key "sub_total" in /in/SO65c on line 17
Warning: Undefined array key "2013-09-17" in /in/SO65c on line 17
Warning: Undefined array key "sub_total" in /in/SO65c on line 17
Warning: Undefined array key "2013-09-16" in /in/SO65c on line 17
Warning: Undefined array key "sub_total" in /in/SO65c on line 17
Array
(
[2013-09-19] => Array
(
[sub_total] => 1566
)
[2013-09-18] => Array
(
[sub_total] => 1542
)
[2013-09-17] => Array
(
[sub_total] => 786
)
[2013-09-16] => Array
(
[sub_total] => 756
)
)
小提琴
您可以在查询时拥有这种数组。类似的东西
select date_field_name, other_field
from table_name
group by Day(date_field_name)
之后,您可以使用使用foreach()
来处理每天的数据!
尝试使用子查询
select field_name,
DAY(date_field) as date,
(
select sum(sub_total)
where DAY(date_field)=date
) as sub_total
from table_name
group by day(date_field)
由于 datetime 表达式的格式始终首先使用其日期子字符串,因此只需隔离第一个空格之前出现的字符。 使用此子字符串进行分组。
检查之前是否遇到过日期。 如果没有,请创建一个引用变量并将其推送到结果数组中。 如果/当再次遇到相同的日期时,将新的小计添加到相关引用中的缓存sub_total中。 对引用变量的所有更改都将反映在结果数组中。
代码:(演示)
$result = [];
foreach ($array as $row) {
$date = strtok($row['placed'], ' ');
if (!isset($ref[$date])) {
$ref[$date] = ['placed' => $date, 'sub_total' => $row['sub_total']];
$result[] = &$ref[$date];
} else {
$ref[$date]['sub_total'] += $row['sub_total'];
}
}
var_export($result);
试试这段代码
$result = array();
foreach($shop as $value)
{
if (!isset($result[$value['placed']]))
{
$result[$value['placed']] = array('placed' => $value['placed'], 'sub_total' => 0);
}
$result[$value['placed']]['sub_total'] += $value['sub_total'];
}
print_r($result);