我有这个数据表:
+-ID-+-sensorID-+----date---+-value-+
| 1 | 1 |'some date'| 20 |
| 2 | 1 |'some date'| 15 |
| 3 | 1 |'some date'| 18 |
| 4 | 2 |'some date'| 40 |
| 5 | 2 |'some date'| 68 |
| 6 | 2 |'some date'| 55 |
现在我想在php中创建一个这样的数组:
date - value sensorID(1) - value sensorID(2)
每当日期只有一个传感器值时,我还需要显示一些内容:
[date] => 01-01-2014 [value] => 50 [value] => 60
[date] => 02-01-2014 [value] => 20 [value] => 30
[date] => 03-01-2014 [value] => null [value] => 55
[date] => 04-01-2014 [value] => 20 [value] => 33
如何通过一些简单的步骤有效地完成这项工作?否则我只会为ID 1和ID 2创建一个结果,或者在整个数组上运行我的函数两次。
答案 0 :(得分:1)
只需在一次运行中获取所有数据并在PHP中构建数组:
// do the mysql query stuff >> $result (array of all rows in db)
$data = array();
foreach ($result AS $row) {
if (!isset($data[$row['date']])) {
$data[$row['date']] = array('sensor1' => null, 'sensor2' => null);
}
$data[$row['date']]['sensor' . $row['sensorID']] = $row['value'];
}
结果将类似于
$data = array(
'01-01-2014' => array('sensor1' => 50, 'sensor2' => 60),
'02-01-2014' => array('sensor1' => 20, 'sensor2' => 30),
'03-01-2014' => array('sensor1' => null, 'sensor2' => 55),
'04-01-2014' => array('sensor1' => 20, 'sensor2' => 33)
);