我正在对每个项目进行计数和求和,并且需要数组看起来像这样。
[Date] =>
[device_type1] => [all the data]
[device_type2] => [all the data]
我正在搜索每个,然后所有人都返回一个日期,我需要所有这些都在这个日期之下,并且在该数组内部将每个设备保持为关键并且在所有设备内部信息。这是我到目前为止所做的。
$all_device_types = array('pole','covert','firewatch','internet','trailer','slave','project');
foreach ($all_device_types as $adt) {
$du->select("CONCAT(YEAR(uptime_date),'-',MONTH(uptime_date),'-',DAY(uptime_date)) as year_month_day,
SUM(uptime_router) as router,
COUNT(uptime_router) as router_count,
uptime_device_type as device_type,
date(uptime_date) as data_date","
WHERE uptime_device_type = '".$adt."'
GROUP BY CONCAT(YEAR(uptime_date),'-',MONTH(uptime_date),'-',DAY(uptime_date))
ORDER BY uptime_date ASC");
$all_results = array();
while( $all_row = $du->fetch() ){
if ($adt == $all_device_types[0]) {
$dates[] = $all_row['data_date'];
$adt_0 = $all_row;
} elseif ($adt == $all_device_types[1]) {
$adt_1[] = $all_row;
} elseif ($adt == $all_device_types[2]) {
$adt_2[] = $all_row;
} elseif ($adt == $all_device_types[3]) {
$adt_3[] = $all_row;
} elseif ($adt == $all_device_types[4]) {
$adt_4[] = $all_row;
} elseif ($adt == $all_device_types[5]) {
$adt_5[] = $all_row;
} elseif ($adt == $all_device_types[6]) {
$adt_6[] = $all_row;
}
}
}
其中一个结果就是这样。
[pole] => Array
(
[year_month_day] => 2017-9-5
[router] => 4408
[router_count] => 4620
[device_type] => pole
[data_date] => 2017-09-05
)
答案 0 :(得分:0)
看起来它可以简化很多。您可以将设备类型添加到GROUP BY,并在单个查询中获取所有结果,而不是循环设备类型并为每个类型运行单独的查询。
我认为CONCAT(YEAR(uptime_date),'-',MONTH(uptime_date),'-',DAY(uptime_date))
应输出与date(uptime_date)
相同的内容,您应该能够在GROUP BY和ORDER BY子句中使用别名。
$du->select("DATE(uptime_date) as data_date,
uptime_device_type as device_type,
SUM(uptime_router) as router,
COUNT(uptime_router) as router_count,
GROUP BY data_date, device_type
ORDER BY data_date, device_type");
如果我错了并且您确实需要CONCAT版本,请将其添加回来,但主要是将device_type添加到GROUP BY并消除WHERE子句。
然后,当您获取结果时,可以将它们直接插入到您想要的多维结构中。
while( $row = $du->fetch() ) {
$all_results[$row['data_date']][$row['device_type']][] = $row;
// to calculate totals for all the devices for each date
if (!isset($all_results[$row['data_date']]['all_devices']) {
// initialize if not set
$all_results[$row['data_date']]['all_devices'] = [
'router' => 0, 'router_count' => 0];
}
// increment values
$all_results[$row['data_date']]['all_devices']['router'] += $row['router'];
$all_results[$row['data_date']]['all_devices']['router_count'] += $row['router_count'];
}