阅读目录&将文件列表写入文件

时间:2014-09-06 19:57:29

标签: php

试图找出一个读取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>

2 个答案:

答案 0 :(得分: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....";

?>

我对此进行了测试并得到了所需的顺序。

答案 1 :(得分:0)

实际上我不知道为什么会这样排序。但你可以尝试glob

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

只要您不将GLOB_NOSORT作为第二个参数传递,结果将被排序。 但排序功能仍然排序错误。

1
10
2
3

但在你的情况下,你似乎没有这个问题。

使用 GLOB_BRACE ,您还可以搜索{jpg|png|gif}等特殊结尾。而且你也可以保存一些代码行。而不是while,它将是foreach

相关问题