简体   繁体   English

PHP将文件名附加到数组

[英]PHP Append filenames to array

I am trying to append filenames to an array in PHP. 我试图将文件名附加到PHP中的数组。 I have code which reads filenames from a directory "songs" on a server. 我有从服务器上的“歌曲”目录中读取文件名的代码。 I simply want each of these filenames to be added to an array. 我只是希望将每个文件名添加到数组中。 How could I do this? 我该怎么办?

Here is my 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);
}

You're using the same variable in the foreach loop as you're using to hold the filename from readdir() . 您正在foreach循环中使用与用于保留readdir()的文件名相同的变量。 So when you do $items[] = $entry; 因此,当您执行$items[] = $entry; you're adding the iteration variable to the array, not the filename. 您将迭代变量添加到数组,而不是文件名。 There doesn't seem to be any reason to add the filename to the array inside the loop, and you should avoid reusing variables like that, it just causes confusion. 似乎没有任何理由在循环内将文件名添加到数组中,并且您应该避免重用这样的变量,这只会造成混乱。

$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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM