简体   繁体   English

用php在目录中列出图像并添加特定的类

[英]list images in a directory with php and add a specific class

How can i list images in a folder...(which could be any number) and echo them in a list making the sure the first li has a class of "first" and the the last list item has a class of "last" like so... 我如何在文件夹中列出图像...(可以是任意数字)并在列表中回显它们,从而确保第一个li的类别为“ first”,最后一个列表项的类别为“ last”像这样...

<li class="first"><img src="flowing-rock.jpg" /></li>
<li><img src="stones.jpg" alt="Stones" /></li>
<li><img src="grass-blades.jpg" /></li>
<li><img src="ladybug.jpg" alt="Ladybug" /></li>
<li class="last"><img src="pier.jpg" alt="Pier" /></li>

Any help would be appreciated... 任何帮助,将不胜感激...

The following will select the first and last (if they exist), printing them before and after the rest, respectively. 下面将选择第一个和最后一个(如果它们存在),分别在其余的之前和之后打印它们。 These are sorted alphabetically by scandir() . 这些由scandir()按字母顺序排序。

$contents = scandir(DIRECTORY);
array_pop($contents); // Remove "."
array_pop($contents); // Remove ".."
$last = array_pop($contents); // Grab last element
$first = array_shift($contents); // Grab first element

// print elements
if (!is_null($first)) echo "<li class='first'><img src='$first' /></li>\n";
foreach ($contents as $key => $val)
    echo "<li><img src='$val' /></li>\n";
if (!is_null($last)) echo "<li class='last'><img src='$last' /></li>\n";

You can use glob to scan for image files, then check the index of the current array element: 您可以使用glob扫描图像文件,然后检查当前数组元素的索引:

$imgs= glob('/path/to/images/*.jpg');

for ($i=0; $i<count($imgs); $i++) {
 if ($i == 0) $class= ' class="first"';
 else if ($i == count($imgs)-1) $class= ' class="last"';
 else $class= '';
 printf("<li%s><img src=\"%s\" /></li>\n", $class, htmlentities(basename($imgs[$i])));
}

Take out the basename call if you want to keep the directory name. 如果要保留目录名称,请执行basename调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM