With the help of another Stack Overflow post I've now got dynamic tables working correctly. I'm looping though an array and creating multiple tables. This works well.
This is the code I'm using :
foreach ($id as $k => $v) {
$maxcols = $cols[$unit[$k]];
$maxid = $cells[$unit[$k]];
$startid = 1;
// maxcols = 4 // maxid = 8
echo "<table id='table$v'><tr>\n";
for ($i = 1;$i<=ceil($maxid/$maxcols);$i++) {
echo "<tr>\n";
for ($j=1;$j<=$maxcols;$j++) {
if ($startid <= $maxid)
echo " <td class='mark'>ID".$startid++."</td>\n";
else
echo " <td class='mark'> </td>\n";
}
echo "</tr>\n<tr>\n";
for ($j=1;$j<=$maxcols;$j++) {
$p = ($i==1) ? $j : ($j+$maxcols);
echo "<td id='$p'></td>\n";
}
echo "</tr>\n";
}
echo "</table>\n";
}
If maxcols = 4 and maxid = 8 I get a table that looks like this :
Viewing the code for that table I can see each TD has an ID that matches the header ID value. eg : row 1 column 2 TD ID =2 header = ID2
The ID value is being created using this :
$p = ($i==1) ? $j : ($j+$maxcols);
If I change maxcols = 2 then I get a table that looks like this :
However the TD ID values are not matching the Header ID. They go
1,2
3,4
3,4
3,4
How do I make each cell have the correct TD ID ?
Simple solution:
$maxcols = $cols[$unit[$k]];
$maxid = $cells[$unit[$k]];
$startid = 1;
$idCounter = 1;
…
…
for ($j=1;$j<=$maxcols;$j++) {
echo "<td id='$idCounter'></td>\n";
$idCounter++;
}
There's probably a way to do it using $j
, $i
, and $maxcols
, but why complicate things.
If you really only want to assign ids to cells that will have values, you could make this change
echo "<td id='".($idCounter<=$maxid ? $idCounter : "")."'></td>\n";
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.