简体   繁体   中英

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. 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).

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.

What I want to know is what is the most efficient way of doing what I said in the comments beneath the foreach loop?

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. If not, then unlink() the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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