从mysql(组)和数组生成表

时间:2013-01-22 09:12:12

标签: php html

我想生成一个包含数据库数据的表。在一个表中,我有关于员工,任务,日期,时间的数据。

CREATE TABLE IF NOT EXISTS `wh_task_worktime` (
`id_worktime` int(11) NOT NULL AUTO_INCREMENT,
`id_task` int(11) NOT NULL,
`id_worker` int(11) NOT NULL,
`id_customer` int(11) NOT NULL,
`date` date NOT NULL,
`time` int(11) NOT NULL,
PRIMARY KEY (`id_worktime`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;

INSERT INTO `wh_task_worktime` (`id_worktime`, `id_task`, `id_worker`, `id_customer`, `date`, `time`) VALUES
(12, 1, 3, 1, '2013-01-18', 8),
(11, 2, 3, 2, '2013-01-18', 8),
(9, 2, 3, 2, '2013-01-16', 5),
(7, 2, 3, 2, '2013-01-15', 6),
(10, 2, 3, 2, '2013-01-13', 6),
(13, 1, 3, 1, '2013-01-16', 6),

生成表格:

echo '<table style="width: 300px; clear:both;" class="list">';
echo '<tr class="bold">';
echo '<td style="width:100px;">Date</td>';

// Headlines tasks
$query0 = "SELECT z.name FROM ".$prefix."task_worktime cp INNER JOIN ".$prefix."task z ON cp.id_task = z.id WHERE `id_worker`= ".$id_worker." GROUP BY cp.id_task HAVING count(z.name) > 0 ";
$news0 = mysql_query($query0) or die ('Error: ' . mysql_error());
while ($rekord0 = mysql_fetch_assoc($news0)) {
echo '<td>'.$rekord0[name].'</td>';
}
echo "</tr>";

// Here shows VERSES WITH DATE and the number of hours worked (depending on the task)
$query = "SELECT date, time, id_worktime, id_task FROM ".$prefix."task_worktime WHERE id_worker = ".$id_worker." order by date ASC";
$news1 = mysql_query($query) or die ('Error: ' . mysql_error());
$daty = array();
while ($row = mysql_fetch_array($news1)) {
$id_date = $row['date'];
if (!isset($daty[$id_date]))
$daty[$id_date] = array('date' => $row['date'], 'time' => array());

if (!empty($row['time']))
$daty[$id_date]['time'][] = array('time' => $row['time']);
}

/ / DISPLAY HOUR AND DATE
foreach ($daty as $id => $data){
echo '<tr><td>'.$data['date'].' </td>';
foreach ($data['time'] as $worktime){
echo '<td>'.$worktime['time'].'</td>';
}
echo '</tr>';
}
echo '</table>';
echo '<pre>';
print_r($daty);
echo '</pre>';

结果是一张带有空白诗句的表格,而不是我希望它们为零的洞

enter image description here

DATE        Task1   Task2
2013-01-13      6
2013-01-15      6
2013-01-16      5   6
2013-01-18      8   8

作为当天的员工不是它不适用于数据库中的任何条目。最后,我想在这里创建一个这样的表:

DATE        Task1   Task2   Task3
2013-01-01  6       0       2
2013-01-02  4       2       0
2013-01-03  0       8       0

在我刮擦的地方,它没有数据库中的任何条目。每个员工的任务数量可能不同。

感谢您提供有关如何正确生成表格的任何建议。

3 个答案:

答案 0 :(得分:0)

在你输出工作时间的行中,检查一下这样的值:

echo '<td>'.($worktime['time']?$worktime['time']:'0').'</td>';

答案 1 :(得分:0)

试试这个: -

echo '<td>'.(isset($worktime['time'])?$worktime['time']:'0').'</td>';

答案 2 :(得分:0)

SELECT name the columns you want returned
  FROM task_worktime cp 
  LEFT
  JOIN task z 
    ON cp.id_task = z.id 
 WHERE id_worker = '$id_worker' 
 GROUP 
    BY cp.id_task 
HAVING COUNT(*) > 1 

请注意,使用这种方式,GROUP BY会产生意想不到的结果。