[thelist] PHP Logic help
Noah St.Amand
noah at tookish.net
Fri Jan 21 14:55:34 CST 2005
Hi Chris,
Chris Ditty wrote (1/21/05 9:06 AM):
> I guess I didn't explain well enough in the first email. I want to be
> able to display different items on a row with a limit of 2 or 3 items
> per row.
I think I know what you mean, but if not feel free to ignore everything
below:
Start with the code you'd use to show one item per row. I'm going to
simplify it from what you have, but it should be easy to extrapolate:
----------
print('<table'>);
foreach($array as $item) {
print('<tr>');
print("<td>$item</td>");
print('</tr>');
}
print('</table>');
----------
In order to show multiple items on each row, use a counter and the
modulus operator to determine when to show '</tr>' and '<tr>' (i.e.,
when to end the current row and start a new one):
----------
//the number of items to show in each table row
$items_per_row = 3;
//the counter
$i = 0;
print('<table>');
//we know we have to start with a <tr>, so get it over with
print('<tr>');
foreach($array as $item) {
//only show a </tr><tr> if this isn't the first item and
//if $i % $items_per_row is 0 (that is, $i divided by
//$items_per_row leaves no remainder, so we've just
//finished a row and need to start a new one)
if ((($i != 0) && ($i % $items_per_row) == 0)) print('</tr><tr>');
print("<td>$item</td>");
$i++;
}
//if we didn't finish with a full row, fill out the remaining
//table cells with
if (($i % $items_per_row) != 0) {
while (($i % $items_per_row) != 0) {
print('<td> </td>');
$i++;
}
}
//we need a </tr> for the last row
print('</tr>');
print('</table>');
----------
There may be a more efficient way to do this. I've done it this way a
few times, though, and it's always worked. If you want to see the above
code in action, stick this above it:
$array =
array('one','two','three','four','five','six','seven','eight','nine','ten');
You can also change the value of $items_per_row.
What's really fun is when you need to make certain items span multiple
columns (i.e. if they're photos, and some are double or triple width).
The logic gets a little hairy, especially when you get two double width
ones in a row, but the second one doesn't fit in the row, so you need to
get a single width one from later in the set and place it between the
sequential double width ones.
Anyway, let me know if any of this doesn't make sense.
Cheers,
Noah
More information about the thelist
mailing list