2014-09-06 186 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