php - Modifying Column Spans based on Item count -
ho can modify columns can add in colspan
if needed based on number of items in row?
scenarios:
say have 5 items, need 1 row/4 columns, next row 1 column colspan="4"
say have 6 items, need 1 row/4 columns, next row, 2 columns colspan="2"
say have 7 items, need 1 row/4 columns, next row, 2 columns no colspan, + 1 column colspan="2"
here's existing code:
echo '<table width="100%" cellpadding="10" cellspacing="5">' . php_eol; $colspan = 4; $rows = 0; for($i = 0; $i < $tmpct; $i++) { // @ column 0 create new row <tr> if($i % $colspan == 0) { $rows++; echo "<tr>\n"; } // if 1 item in row, need add colspan="4", 2 items colspan="2" 2 <td>'s, 3 items 1 @ colspan="2" + 2 <td>'s echo '<td width="25%" align="center" valign="middle">' . $tmpret[$i]['sponname'] . '</td>' . php_eol; // @ column 3 end row </tr> echo $i % $colspan == 3 ? "</tr>\n" : ""; } // have 5 columns, need create 3 empty <td> validate table! for($j = $i; $j < ($colspan * $rows); $j++) { echo "<td> </td>\n"; } // add final <tr> if(($colspan * $rows) > $i) { echo "</tr>\n"; } echo '</table>';
well, when arithmetic useful !
need use modulo operation @ each level.
here solution:
$tmpret = array( array(1), array(1, 2, 3), array(1, 2, 3, 4, 5, 6, 7), array(1, 2, 3, 4, 5), array(1, 2), array(1, 2, 3, 4, 5, 6), array(), array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16), array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) ); $lencol = count($tmpret); echo '<table border="1" width="800px" cellpadding="10" cellspacing="5">'.php_eol; $colspan = 4; for($i = 0; $i < $lencol; $i++) { $bg = 'style="background-color: #'.rand(100, 999).'"'; $row = $tmpret[$i]; $lc = count($row); $offset = 0; if ($lc>$colspan) { $ct = floor($lc/$colspan); $offset = $ct * $colspan; $m = 0; ($k = 0; $k<$ct; $k++) { echo '<tr '.$bg.' >'; ($l = 0; $l<$colspan; $l++) { echo '<td>'.$row[$m].'</td>'; $m++; } echo '<tr>'; } } $mod = $lc % $colspan; switch ($mod) { case 1: echo '<tr '.$bg.' ><td colspan="4">'.$row[$offset].'</td></tr>'; break; case 2: echo '<tr '.$bg.' ><td colspan="2">'.$row[$offset].'</td><td colspan="2">'.$row[$offset+1].'</td></tr>'; break; case 3: echo '<tr '.$bg.' ><td>'.$row[$offset].'</td><td>'.$row[$offset+1].'</td><td colspan="2">'.$row[$offset+2].'</td></tr>'; break; } } echo '</table>';
and looks like:
hope helps
edit: works $colspan=4
, if need things more dynamic think of replacing switch statement else... maybe nested loops...
Comments
Post a Comment