2013-11-01 31 views
1

我有工作代碼,它從動態創建的文件夾中提取所有圖像。但是我想在顯示頁面中只顯示來自特定文件夾的一個圖像。有什麼建議麼? 我的代碼:如何從php文件夾中只拉出1張圖片?

<?php 
    $search_dir = "$directory/{$row['name']}{$row['hotel_address']}"; 
    $images = glob("$search_dir/*.jpg"); 
    sort($images); 
    //display images 
    foreach ($images as $img) { 
     echo "<img src='$img' height='150' width='150' /> "; 
    } 

?> 
+1

歡迎堆棧溢出!如果你自己解決問題並[描述你所嘗試的](http://whathaveyoutried.com),我們更有可能幫助你。檢查堆棧溢出[問題清單](http://meta.stackexchange.com/questions/156810/stack-overflow-question-checklist)以獲取有關詢問正確問題的更多信息。祝你好運,快樂的編碼! –

回答

1

您可以顯示一個圖像:

<?php 
    $search_dir = "$directory/{$row['name']}{$row['hotel_address']}"; 
    $images = glob("$search_dir/*.jpg"); 
    sort($images); 

    // Image selection and display: 

    //display first image 
    if (count($images) > 0) { // make sure at least one image exists 
     $img = $images[0]; // first image 
     echo "<img src='$img' height='150' width='150' /> "; 
    } else { 
     // possibly display a placeholder image? 
    } 

?> 

如果你想有一個隨機的形象,做到這一點:

// Image selection and display: 

    //display random image 
    if (count($images) > 0) { // make sure at least one image exists 

     // Get a random index in the array with rand(min, max) which is inclusive 
     $randomImageIndex = rand(0, count($images)-1); 
     $img = $images[$randomImageIndex]; // random image 
     echo "<img src='$img' height='150' width='150' /> "; 

    } else { 
     // possibly display a placeholder image 
    } 
+0

非常感謝你,泰迪!它確實有幫助。讚賞。 其實每個文件夾裏面都有很多圖片。我想要的是,它首先只顯示一個圖像。一旦人們刷新或重新加載頁面,它會隨機顯示來自所關注文件夾的下一個圖像。 –

+0

[現在它只顯示來自其各自文件夾的1張圖像] 實際上,每個文件夾內都有很多圖像。我想要的是,它首先只顯示一個圖像。一旦人們刷新或重新加載頁面,它會隨機顯示來自所關注文件夾的下一個圖像。 –

+0

泰迪先生!你是天才。非常感謝。它運作良好,完美。 再次感謝。上帝祝福你。 –

1

您可以使用current從數組中得到的第一個圖像。

<?php 
$search_dir = "$directory/{$row['name']}{$row['hotel_address']}"; 
$images = glob("$search_dir/*.jpg"); 
sort($images); 
//display one image: 
echo "<img src='current($images)' height='150' width='150' /> "; 
?> 
相關問題