dopuz8728 2014-09-06 19:57
浏览 24
已采纳

读取目录并将文件列表写入文件

Trying to figure out a read a directory of php files and write to another file. It works fine except that the first file is being put last in the file.

Can someone help point me in the right direction to modify my code to put the file names in the proper order? The file name will be different at times but I'm hoping to keep them in the same order they are in the directory.

Thanks Bob

<?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>
";
        fwrite($myfile, $txt);
        fclose($myfile);
    }
    closedir($handle);
    echo "Build completed....";
}

?> 

It keeps putting the first file last

<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条回答 默认 最新

  • douzuqin3467 2014-09-06 21:15
    关注

    Data structures are your friend. So, instead of readdir() try using scandir() to get an array of filenames.Then loop through this array to generate a second array of iframe strings. Then implode this second array and fwrite the resultant string.

    Here's what it might look like:

    <?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>
    ";
    }
    
    $myfile = fopen("$dirDestination/iframe.php", "a") or die("Unable to open iframe.php file!");
    fwrite($myfile, implode($txt_ary));
    fclose($myfile);
    
    echo "Build completed....";
    
    ?>
    

    I tested this and got the desired ordering.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答