Kevin Kevin - 1 month ago 5
PHP Question

Modifying Column Spans based on Item count

Ho can I modify my columns so I can add in a

colspan
if needed based on the number of items in the row?

Scenarios:

Say I have 5 Items, I need one row/4 columns, next row 1 column with colspan="4"

Say I have 6 Items, I need 1 row/4 columns, next row, 2 columns with colspan="2"

Say I have 7 Items, I need 1 row/4 columns, next row, 2 columns no colspan, + 1 column with colspan="2"

Here's my existing code:

echo '<table width="100%" cellpadding="10" cellspacing="5">' . PHP_EOL;

$colSpan = 4;
$rows = 0;
for($i = 0; $i < $tmpCt; $i++) {
// At column 0 you create a new row <tr>
if($i % $colSpan == 0) {
$rows++;
echo "<tr>\n";
}
// if only 1 item in the row, need to add colspan="4", 2 items colspan="2" for 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;

// At column 3 you end the row </tr>
echo $i % $colSpan == 3 ? "</tr>\n" : "";
}
// Say you have 5 columns, you need to create 3 empty <td> to validate your table!
for($j = $i; $j < ($colSpan * $rows); $j++) {
echo "<td>&nbsp;</td>\n";
}
// Add the final <tr>
if(($colSpan * $rows) > $i) {
echo "</tr>\n";
}


echo '</table>';

Answer

Well, that when arithmetic is useful !
What you need is to use the modulo operation at each level.

Here is my 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;
    for ($k = 0; $k<$ct; $k++) {
      echo '<tr '.$bg.' >';
      for ($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 this is what it looks like:

example

Hope this helps

EDIT: this works only for $colspan=4, if you need things to be more dynamic think of replacing the switch statement with something else... maybe nested loops...

Comments