簡體   English   中英

使用opendir()顯示前5個文件名,使用PHP顯示$ file

[英]Display the first 5 file names using opendir() and $file using PHP

$ d = opendir(“ docs”);

while (($file = readdir($d)) !== false) { 

    if (($file != ".") && ($file != "..")){
        }
}

我希望能夠顯示前5個文件名。

這是一個問題,我有一個下一步按鈕,我想顯示接下來的5個文件名

謝謝讓

您可以使用一個計數器變量,並確保它不會超過5?

有點像:

$counter = 0;
$d = opendir("docs");
while (($file = readdir($d)) !== false && $counter < 5) { 
    if (($file != ".") && ($file != "..")){
        // ...
        $counter++;
    }
}


未測試:也許您必須使用<=代替<

您可以先將所有文件放入一個數組中。 然后使用循環遍歷數組,步驟為5。

$filenames = array_filter(glob($path.'*'), 'is_file'); 

您可以如下使用計數器:

$d = opendir("docs");
// check for opendir error here.

$count = 0; // initialize counter.

while (($file = readdir($d)) !== false) { 

    if (($file != ".") && ($file != "..")){
        //....process files here.

        $count++; // done with one file..increment counter.
        if($count == 5) // have we reached the limit ?
            break; // if yes break.


    }
}

@編輯的問題

我建議下一個按鈕提交表單或以某種方式創建新請求? 因此,只需傳遞當前的計數器值即可。

$counterLimit = 5;
$counterStart = $_POST['counterStart']; //Pass the start value
$counterEnd= ($counterLimit + $counterStart);
$dir = opendir("dir");
$i = 0;
while (($file = readdir($dir) !== false) && ($i <= $counterEnd)) {
   if ($i >= $counterStart) {
       //Do something
   }
   $i++;
}

未經測試。 但是那樣。

$from = GET["from"];

$counter = 0;
$fileCounter = 0;
$d = opendir("docs");
while (($file = readdir($d)) !== false && $counter < 5) { 
    if (($file != ".") && ($file != "..") && $from == $fileCounter){
        // ...
        $counter++;
    } else {
        $fileCounter++;
    }
}

上面的代碼不是testet,但是它應該可以這樣工作。

在下一個按鈕上,您現在擁有類似於files.php?from = 5之類的東西,可以從5-10中獲取文件。

暫無
暫無

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

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