Page 1 of 1

Looping images into table for gallery?

Posted: Fri Nov 19, 2004 5:33 am
by bradles
Hi All,

Does anyone know a good way of looping 12 images into a table that is 3 columns x 4 rows?

I was thinking of setting up an outer loop for the rows and an inner loop for the columns. Something like:

Code: Select all

echo "<table>\n";
	//Row Setup
	for ( $y = 1; $y <=4; $y++ ) {
		echo "	<tr>\n";
		
		//Column Setup
		for ( $x = 1; $x <=3; $x++ ) {
			echo "<td>\n";
			//Image gets put here
			echo "</td>\n";	
		}
		
		echo "	</tr>\n";
	}
echo "</table>\n";
This looks like it could get pretty messy. Is there an easier way out there of doing this?

Brad.

Posted: Fri Nov 19, 2004 7:21 am
by peni
no, as long as you keep your code clean and understandable, this is a good solution. you can put the inner for() into an extern function and call it, but it's not necessary, due to the fact that you can quickly vary the rows/cols count this way.

Posted: Fri Nov 19, 2004 9:02 am
by timvw
Now all that you need to do is make it a little more flexible (so you can reuse it)

Code: Select all

/*
 * make HTML to display images
 *
 * @param $images an array with assoc arrays that have keys src and alt
 * @param $rows the number of rows
 * @param $cols the number of columns
 * @return the generated HTML
*/

function makeGallery($images, $rows, $cols)
{
  $html = '';
  for ($i = 0; $i < $rows; ++$i)
  {
    $html .= '<tr>';
    for ($j = $j < $cols; ++$j)
    {
      $html .= '<td><img src="{$images[(($i * $cols) + $j)]['src'}" alt="{$images['(($i * $cols) + $j)]['alt']" /></td>';
      }
    $html .= '</tr>';
  }
  return $thml;
}

Posted: Fri Nov 19, 2004 10:27 am
by pickle
You can do it with only 1 loop:

Code: Select all

$number_of_images = 12;
$images_per_row = 4;
echo "<table><tr>";
for($col_counter = 1; $col_counter <= $number_of_images; ++$col_counter)
{

    //this is what breaks up your rows
   if($col_counter%$images_per_row == 0)
   {
     echo "</tr><tr>";
   }

    echo "<td>";
    //dump image here
    echo "</td>";
}
echo "</tr></table>";