我有一个从数组动态创建的表。使用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";
?>
答案 0 :(得分:2)
在每一行上,您可以检查&#34;上面的单元格&#34;是相同的,如果是,则取消写入。并且,您可以计算&#34;以下单元格的数量&#34;计算你必须写的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>
答案 1 :(得分:0)
我会将您的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提供)