简体   繁体   English

从PHP中的循环删除文件

[英]Deleting Files from a Loop in PHP

So currently I have two loops running within another ( I don't know if this is like taboo or something :D ) But what I'm aiming for is if the number of files in a directory (Pages) are more than in another directory (Posts), I want it to delete the corresponding files in the Pages folder. 因此,当前我在另一个循环中运行两个循环(我不知道这是否像是忌讳之类的东西:D),但我的目标是目录(页面)中的文件数是否大于另一个目录中的文件数(帖子),我希望它删除Pages文件夹中的相应文件。 All the files in the Pages folder are numbered, and every time there is a new text file in the Posts directory, there is a corresponding page created in the Pages directory with the same number (ie, 12.txt will create 12.html). Pages文件夹中的所有文件都已编号,并且每次在Posts目录中都有一个新的文本文件时,都会在Pages目录中创建一个具有相同编号的对应页面(即12.txt将创建12.html)。 。

Here is what I got: 这是我得到的:

<?php
if($postcount<=$pagecount){
 do{
  foreach(glob($pagedir . "*html")as $filename);
  //something in here to remove the .html, calculate what is above the $postcount
  //number, then unlink the files that don't meet the while loop
 }
 while($postcount<=$pagecount);
?>

I'm still really trying to wrap my head around foreach loops, so perhaps the one I have isn't right, or I don't even need it. 我实际上仍然在尝试把头缠在foreach循环上,因此,也许我不正确,或者甚至不需要它。

What I want to know is what is the most efficient way of doing what I said in the comments beneath the foreach loop? 我想知道什么是做我在foreach循环下面的评论中所说的最有效的方法?

You can use a function to compare the 2 directories, then just remove the files that aren't the same. 您可以使用一个函数比较两个目录,然后删除不相同的文件。

Look at the function at this link 查看此链接上的功能

You just need to modify it a bit so it checks for the different file names in the directories, but what you would then want to do is loop through the returned array, and just unlink the files. 您只需要稍作修改,就可以检查目录中不同的文件名,但是您要做的是遍历返回的数组,然后取消链接文件。

I'd recommend making an array from the first directory. 我建议从第一个目录创建一个数组。 Then run through the second directory and use in_array() to determine if it's in the last folder. 然后遍历第二个目录并使用in_array()确定它是否在最后一个文件夹中。 If not, then unlink() the file. 如果不是,则取消链接()文件。

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

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