duanchuanqu593743 2017-06-23 02:53
浏览 43
已采纳

使用PHP从文件和目录数组中删除文件

I'm trying to get a list of directories in a path by using scandir and removing the files from the array but I'm getting errors from my echo.

I'm using the code

$path = "Calltypes/";
$files = scandir($path);
$files = array_diff(scandir($path), array('.', '..'));

for($i = 0; $i < sizeof($files); $i++) {
    if(!is_dir($files[$i]))
        array_splice($files, $i, 1);
}

echo sizeof($files);

This is the echo output:

Notice: Undefined offset: 0 in C:\xampp\htdocs\index.php on line 32
2

The Calltypes/ path has 3 folders and 1 txt file.

Edit: line 32 is

if(!is_dir($files[$i]))
  • 写回答

2条回答 默认 最新

  • dougou8552 2017-06-23 03:01
    关注

    You can use foreach instead of for. After that use unset because array_splice will rearrange keys so you will get errors

    $path = "Calltypes/";
    $files = scandir($path);
    $files = array_diff(scandir($path), array('.', '..'));
    
    foreach ($files as $key => $value) {
        if(!is_dir($path.$files[$key]))
           unset($files[$key]);
    }
    echo sizeof($files);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部