|
/* * Find a list of images in /images and provide thumbnails */ function get_table ( $limit_start = 0, $limit_step = 5 ) { $images = get_image_list('images'); // Generate navigation for Previous and Next buttons // Code given below $output .= '<table class="image_table">'; $columns = 5; foreach ($images as $index => $image) { // Begin directory listing at item number $limit_start if ( $index < $limit_start ) continue; // End directory listing at item number $limit_end if ( $index >= $limit_start + $limit_step ) continue; // Begin column if ( $index - $limit_start % $columns == 0 ) { $output .= '<tr>'; } // Generate link to blown up image (see below) $thumbnail = '<img src="http://www.ASPcool.com/lanmu/thumbnails/' . $image . '" />'; $output .= '<td>' . get_image_link($thumbnail, $index) . '</td>'; // Close column if ( $index - $limit_start % $columns == $columns - 1 ) { $output .= '</tr>'; } } $output .= '</table>'; return $nav . $output; } 这个表很简单,它从索引号 $limit_start 开始遍历图片列表。然后放上每个图片的缩略图,每五张图片作为一行。达到 $limit_start + $limit_step 的时候循环结束。 该表是目录列表的可视化表示,因此需要一个函数列出目录中的所有图像。清单 1 中的 get_file_list() 函数用索引数组返回 /images 目录中的所有图片列表。下面是一个示例实现。 清单 2. get_file_list 实现 function get_image_list ( $image_dir ) { $d = dir($image_dir); $files = array(); if ( !$d ) return null; while (false !== ($file = $d->read())) { // getimagesize returns true only on valid images if ( @getimagesize( $image_dir . '/' . $file ) ) { $files[] = $file; } } $d->close(); return $files; } 注意:本文后面还要使用 get_file_list() 函数。有一点很重要,无论何时调用该函数,返回的数组都是不变的。因为提供的实现要进行目录搜索,必须保证目录中的指定文件不会改变,每次都要按字母顺序排序。 导航的实现 虽然表格列出了目录中的一些图像,但用户还需要一种查看表格中未出现的图片的方法。要真正实现分页器的导行,则需要一套标准的链接:首页、上一页、下一页和尾页。 清单 3. 分页器导航 // Append navigation $output = '<h4>Showing items ' . $limit_start . '-' . min($limit_start + $limit_step - 1, count($images)) . ' of ' . count($images) . '<br />'; $prev_start = max(0, $limit_start - $limit_step); if ( $limit_start > 0 ) { $output .= get_table_link('<<', 0, $limit_step); $output .= ' | ' . get_table_link('Prev', $prev_start, $limit_step); } else { $output .= '<< | Prev'; } // Append next button $next_start = min($limit_start + $limit_step, count($images)); if ( $limit_start + $limit_step < count($images) ) { $output .= ' | ' . get_table_link('Next',$next_start, $limit_step); $output .= ' | ' . get_table_link('>>',(count($images) - $limit_step), $limit_step); } else { $output .= ' | Next | >>'; } $output .= '</h4>'; 最后还要编写 get_image_link() 和 get_table_link() 函数,让用户将缩略图展开成完整的图像(参见清单 4)。注意,脚本 index.PHP(以及后面要创建的 expand.php)只在这两个函数中调用。这样就很容易改变链接的功能。事实上在下面与 Sajax 进行集成时,只有这两个函数需要修改。 清单 4. get_image_link、get_table_link 实现 function get_table_link ( $title, $start, $step ) { $link = "index.PHP?start=$start&step=$step"; return '<a href=http://www.ASPcool.com/lanmu/"' . $link . '">' . $title .'</a>'; } function get_image_link ( $title, $index ) { $link = "expand.PHP?index=$index"; return '<a href=http://www.ASPcool.com/lanmu/"' . $link . '">' . $title . '</a>'; } |