我有一个看起来像这样的表格。
pers_id pers_name pers_date pers_date_attend_ind
431 Bacon 1/14/2013 N
431 Bacon 1/27/2013 N
431 Bacon 1/28/2013 N
431 Bacon 2/17/2013 N
我想用 php 来显示它
<date 1> <date 2> <Date 3>
Bacon N N N
我不知道该怎么做。
最佳答案
假设您的 $rows
变量在获取结果后将如下所示:
$rows = array(0 => array('pers_id' => 431, 'pers_name' => 'Bacon', 'pers_date' => '1/14/2013', 'pers_date_attend_ind' => 'N'),
1 => array('pers_id' => 431, 'pers_name' => 'Bacon', 'pers_date' => '1/27/2013', 'pers_date_attend_ind' => 'N'),
2 => array('pers_id' => 431, 'pers_name' => 'Bacon', 'pers_date' => '1/28/2013', 'pers_date_attend_ind' => 'N'),
3 => array('pers_id' => 431, 'pers_name' => 'Bacon', 'pers_date' => '2/17/2013', 'pers_date_attend_ind' => 'N'),
);
然后我使用这个数组使其看起来像这样:
Array
(
[431] => Array
(
[name] => Bacon
[dates] => Array
(
[1/14/2013] => N
[1/27/2013] => N
[1/28/2013] => N
[2/17/2013] => N
)
)
)
使用foreach
循环:
foreach($rows as $value)
{
$array[$value['pers_id']]['name'] = $value['pers_name'];
$array[$value['pers_id']]['dates'][$value['pers_date']] = $value['pers_date_attend_ind'];
}
现在,您的 table 准备工作看起来好多了。我创建了一个函数,它根据此修改后的数组返回您在问题中设置的表。
function generate_table($array)
{
$html = '';
foreach($array as $value)
{
$html .= '<table>'; // start table inside the loop. It will looks better due to each member may have different number of date count.
$html .= '<tr>';
$html .= '<td> </td>';
foreach($value['dates'] as $k => $v)
{
$html .= '<td>' . $k . '</td>';
}
$html .= '</tr>';
$html .= '<tr>';
$html .= '<td>' . $value['name'] . '</td>';
foreach($value['dates'] as $v)
{
$html .= '<td>' . $v . '</td>';
}
$html .= '</tr>';
$html .= '</table>';
}
return $html;
}
这个函数看起来有点恶心,但它确实有效。如果您愿意,您可以改进此功能。
实时预览
结果预览
关于php - 如何在一行中显示签到表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25766716/