簡體   English   中英

用php在目錄中列出圖像並添加特定的類

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

我如何在文件夾中列出圖像...(可以是任意數字)並在列表中回顯它們,從而確保第一個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>

任何幫助,將不勝感激...

下面將選擇第一個和最后一個(如果它們存在),分別在其余的之前和之后打印它們。 這些由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";

您可以使用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])));
}

如果要保留目錄名稱,請執行basename調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM