PHP将文件名附加到数组

时间:2017-04-14 21:12:12

标签: php arrays file append

我正在尝试将文件名附加到PHP中的数组中。我有代码从目录中读取文件名"歌曲"在服务器上。我只想将每个文件名添加到一个数组中。我怎么能这样做?

这是我的PHP。

$target = "songs/"; 
$items = array();
if ($handle = opendir($target)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            foreach($song as $entry) {
                $items[] = $entry; 
            }

            //echo $items;
            echo $entry."\n";
        }
    }
    closedir($handle);
}

1 个答案:

答案 0 :(得分:1)

您正在foreach循环中使用相同的变量来保存readdir()中的文件名。所以,当你执行$items[] = $entry;时,你将迭代变量添加到数组中,而不是文件名。似乎没有任何理由将文件名添加到循环内的数组中,并且应该避免重复使用这样的变量,这只会引起混淆。

$items = array();
if ($handle = opendir($target)) {
    while ($entry = readdir($handle)) {
        if ($entry != "." && $entry != "..") {
            $items[] = $entry;
            foreach($song as $s) {
                // do something with $s
            }

            //echo $items;
            echo $entry."\n";
        }
    }
    closedir($handle);
}