我有一个从数组动态创建的表。使用PHP,如何在重复数据时动态添加rowspan?我希望'Youth Classes'只显示一次并且rowspan = 2。
Array
(
[0] => Array
(
[Type] => Youth Classes
[Class] => Preschool Class
[Day] => Saturday
)
[1] => Array
(
[Type] => Youth Classes
[Class] => Grade School
[Day] => Friday
)
)
<?php
/*Load csv file into array*/
$file = 'list.csv';
$rows = array_map('str_getcsv', file($file));
$headers = array_shift($rows);
$csv = array();
foreach($rows as $row) {
$csv[] = array_combine($headers, $row);
}
/*Build Table*/
echo "\t\t<table class='table'>\n";
echo "\t\t\t<tr>\n";
foreach ($headers as $header) {
echo "\t\t\t\t<th>";
echo $header;
echo "</th>\n";
}
echo "\t\t\t</tr>\n";
foreach ($csv as $row) {
echo "\t\t\t<tr>\n";
foreach ($row as $cell) {
echo "\t\t\t\t<td>";
echo $cell;
echo "</td>\n";
}
echo "\t\t\t</tr>\n";
}
echo "\t\t</table>\n";
?>
在每一行上,您可以检查“上方单元格”是否相同,如果是,则取消写入。并且,您可以计算“低于单元格”的数量是相同的,以计算您必须编写的rowspan
的数量。
如果两行或更多行相同,则以下代码有效。
/*Build Table*/
echo "\t\t<table class='table'>\n";
// Your header code skipped here...
foreach ($csv as $rid => $row) { // Add key $rid here
echo "\t\t\t<tr>\n";
foreach ($row as $cid => $cell) { // Add key $cid here
// If above cell is the same, skip.
if ($rid > 0 && isset($csv[$rid-1]) && $csv[$rid-1][$cid] == $cell)
continue;
// Check amount of "below cells" that are the same :
$rspan = 1 ; $idx = 1 ;
while (isset($csv[$rid + $idx]) && $csv[$rid + $idx][$cid] == $cell) {
$rspan++;
$idx++;
}
// Write rowspan if needed.
echo "\t\t\t\t<td".($rspan > 1 ? ' rowspan="' . $rspan . '"' : '') . ">";
echo $cell;
echo "</td>\n";
}
echo "\t\t\t</tr>\n";
}
echo "\t\t</table>\n";
产出:
<table class='table'>
<tr>
<td rowspan="2">Youth Classes</td>
<td>Preschool Class</td>
<td>Saturday</td>
</tr>
<tr>
<td>Grade School</td>
<td>Friday</td>
</tr>
</table>
我会将您的csv数据分组为多维数组,然后计算每个类别中的行数。这将决定喂rowspan
的价值,如果rowspan
甚至需要写。
代码:(Demo)
$csv=<<<CSV
Youth Classes,Grade School,Monday
Adult Classes,Grade School,Tuesdayday
Youth Classes,Grade School,Friday
Youth Classes,Preschool Class,Saturday
CSV;
foreach (explode("\n", $csv) as $line) {
$row = str_getcsv($line, ",");
$grouped[array_shift($row)][] = $row;
}
//var_export($grouped);
echo "<table>\n";
foreach ($grouped as $category => $group) {
$rows=sizeof($group);
foreach ($group as $i => $row) {
echo "\t<tr>\n";
if(!$i){ // if this is the first row of the subarray (in other words: [0])
echo "\t\t<th" , ($rows>1 ? " rowspan=\"$rows\"" : "") , ">$category</th>\n";
}
echo "\t\t<td>" , implode("</td>\n\t\t<td>", $row) , "</td>\n";
echo "\t</tr>\n";
}
}
echo "</table>";
来源输出:
<table>
<tr>
<th rowspan="3">Youth Classes</th>
<td>Grade School</td>
<td>Monday</td>
</tr>
<tr>
<td>Grade School</td>
<td>Friday</td>
</tr>
<tr>
<td>Preschool Class</td>
<td>Saturday</td>
</tr>
<tr>
<th>Adult Classes</th>
<td>Grade School</td>
<td>Tuesdayday</td>
</tr>
</table>
渲染输出:(由phptester.com提供)