帮助嵌套的foreach循环

I am trying to ultimately find files in a directory that are no longer being used and delete them. I am using a field in my database to match against the filenames; they are the same.

The outer loop is for the database values and the inner loop is for the files in the directory. I'm using an if stmt inside the inner loop but I am getting files showing up in the output that should not be there. What am I doing wrong?

If I have a file in my directory and no matching database value, I want to delete the file.

                foreach( $ds as $id ){
                    foreach( $out as $file ){
                        if( $file != $id['patient_id'] ){
                            echo $id['patient_id'];
                        }
                    }
                }

Furthering @DarkDust's answer, a fairly efficient way of doing it (assuming you're using raw PHP as opposed to a framework) would be something along the lines of:

$files = array()
$rows = array();

while($add = mysql_fetch_array(mysql_query('SELECT filename FROM files')) {
  $rows[] = $add[0]
}

...files code

foreach(array_diff($files, $rows) as $deletable) {
  unlink('/path/to/'.$deletable);
}

I'd say using nested foreach loops for this in the first place is a bad idea; and also it looks to me logically that you have these the wrong way round- shouldn't file be on the outside?

I'd suggest building an array from your database then looping over the files as you are there and do an in_array to determine whether or not to delete them- the way you're doing it would loop over all the files for every row of results; that can't be good.

I don't do any PHP any more so I can't give you a concrete answer, but I can tell how such a problem can be solved on a higher level: what you want is to know whether some entries in a set (files on disk) are not in another set (database). You can solve this with a set difference: set(files on disk) - set(database) = set(files to delete). So you first need an array that has all the entries of your db's patient_id fields. You already seem to have an array with the filenames. It seems that to calculate the set difference on PHP, you can use the array_diff method as in:

$files_to_delete = array_diff($out, $patient_ids)

Sorry for the vague answer, hope it's of use nevertheless.