2014-09-06 96 views
1

試圖找出讀取php文件的目錄並寫入其他文件。它工作正常,除了第一個文件放在文件的最後。讀取目錄並將文件列表寫入文件

有人可以幫助指向正確的方向來修改我的代碼,以正確的順序將文件名?文件名有時會有所不同,但我希望保持它們在目錄中的順序。

感謝 鮑勃

<?php 

$dirDestination = "build"; 

$path = "build/combine"; 

if ($handle = opendir($path)) { 
    while (false !== ($file = readdir($handle))) { 
     if ('.' === $file) continue; 
     if ('..' === $file) continue; 

     $myfile = fopen("$dirDestination/iframe.php", "a") or die("Unable to open iframe.php file!"); 
     $txt = "<iframe src =\"$file\" width=\"780\" height=\"1100\"> </iframe>\n"; 
     fwrite($myfile, $txt); 
     fclose($myfile); 
    } 
    closedir($handle); 
    echo "Build completed...."; 
} 

?> 

它不斷把最後的第一個文件

<iframe src ="item2.php" width="780" height="1100"> </iframe> 
<iframe src ="item3.php" width="780" height="1100"> </iframe> 
<iframe src ="item4.php" width="780" height="1100"> </iframe> 
<iframe src ="item1.php" width="780" height="1100"> </iframe> 

回答

1

數據結構是你的朋友。因此,不要使用readdir()嘗試使用scandir()來獲取數組的文件名。然後循環訪問該數組以生成iframe字符串的第二個數組。然後implode這第二個數組和fwrite結果字符串。

下面是它可能是什麼樣子:

<?php 

$dirDestination = "build"; 
$path = "build/combine"; 

$txt_ary = array(); 
$dir_ary = scandir($path); 

foreach ($dir_ary as $file) { 
    if ($file === '.' || $file === '..') continue; 
    $txt_ary[] = "<iframe src =\"$file\" width=\"780\" height=\"1100\"> </iframe>\n"; 
} 

$myfile = fopen("$dirDestination/iframe.php", "a") or die("Unable to open iframe.php file!"); 
fwrite($myfile, implode($txt_ary)); 
fclose($myfile); 

echo "Build completed...."; 

?> 

我測試這一點,得到了所需的排序。

+0

工作非常好,謝謝。我整天都在嘗試很多不同的方式。 – bpross 2014-09-06 21:40:50

+0

我很高興bpross。 – Joseph8th 2014-09-06 21:51:31

0

其實我不知道爲什麼它按這種方式。但您可以嘗試glob

$files = glob("mypath/*.*"); 

只要你不傳遞GLOB_NOSORT作爲第二參數,結果將被排序。 但排序功能仍然排序數字錯誤。

1 
10 
2 
3 

但在你的情況下,你似乎沒有這個問題。

With GLOB_BRACE您還可以搜索特殊結局,如{jpg|png|gif}。你也可以保存一些代碼。而不是while這將是一個foreach

+0

我讀scandir自動掃描也順序。我試圖讓你或其他工作。 – bpross 2014-09-06 21:16:58

+0

@bpross如果我嘗試編碼,我總是尋找最短的可能性來完成我的任務:) – Dwza 2014-09-06 21:18:47