对于在数组中的每个项目上运行函数都不太了解,对PHP来说还不是很新,$pic_loc
下面是来自MySQL的数据数组,包含匹配任何搜索条件的图像的路径和文件名
试图让unlink
函数在它找到的每个人身上运行。没有错误返回。我不认为foreach
是正确的方法,有人能指出我正确的方向吗?
$pic_loc = $cell_pictures['pic_loc']; //gathers an array from the database of files locations
$pics_to_delete .= "../../".$pic_loc; //corrects the directory
foreach($pics_to_delete as $pics_being_deleted) //deletes all pictures found
{
unlink($pics_being_deleted);
}
编辑:
我用两个答案修补它很多,我知道我可以删除2层文件,因为我可以为单个文件做到没有问题。这就是我目前正在做的事情,我摆脱了while()
循环,可能会导致foreach运行的问题:
$data_array2 = mysql_query("SELECT * FROM pictures WHERE user_id = '".$id."'");
$cell_pictures = mysql_fetch_array($data_array2);
foreach($cell_pictures['pic_loc'] as $pics_being_deleted) //deletes all pictures found
{
unlink("../../".$pics_being_deleted);
}
这是它现在返回的错误:
Warning: Invalid argument supplied for foreach() // on the line that the foreach is on
编辑: 好吧那是搞砸了,但我知道了!您会认为来自查询的数据将是一个数组,但实际上您不必将其设置为数组。我就这样做了:
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
while($cell_pictures = mysql_fetch_array($data_array2))
{
$the_pics = $cell_pictures['pic_loc'];
$pics_as_array = array($the_pics);
}
foreach($pics_as_array as $pics_being_deleted)
{
unlink("../../".$pics_being_deleted);
}
这很好用。感谢一大堆花时间阅读本文! -Mike
答案 0 :(得分:2)
实际上foreach
对你想做的事情完全没问题。
但是,您需要将一些逻辑放在迭代中。我们来看看:
$directory = realpath("../../"); // the directory where files are placed
foreach ($pics_to_delete as $basename) //deletes all pictures found
{
$path = sprtinf('%s/%s', $directory, $basename);
unlink($path);
}
更好的选择是反过来做。首先获取目录及其中的所有文件,然后针对要删除的文件过滤该列表。只有名称匹配时,继续:
$dir = new DirectoryIterator($path);
$toDelete = new DeleteFilter($dir, $pics_to_delete);
foreach ($toDelete as $file)
{
printf("Delete: %s\n", $file->getPathname());
unlink($file->getPathname());
}
DirectoryIterator
附带PHP,DeleteFilter
是一个小FilterIterator
,它确保只返回真正的文件匹配并从$pics_to_delete
数组输入:
class DeleteFilter extends FilterIterator
{
private $filenames;
public function __construct(Iterator $iterator, array $filenames)
{
$this->filenames = $filenames;
parent::__construct($iterator);
}
public function accept()
{
$current = $this->getInnerIterator()->current();
if (!($current instanceof SplFileInfo)) {
return FALSE;
}
if (!$current->isFile()) {
return FALSE;
}
return in_array($current->getBasename(), $this->filenames);
}
}
你不需要那个过滤迭代器,而是你可以在foreach
内编写那个逻辑,不过我觉得这个更流畅。
答案 1 :(得分:1)
如果$ cell_pictures ['pic_loc']是要删除的文件数组,那么
foreach($cell_pictures['pic_loc'] as $pics_being_deleted) //deletes all pictures found
{
unlink("../../".$pics_being_deleted);
}
答案 2 :(得分:0)
有时,网络托管主机设置是您无权删除或访问任何文件夹,文件高于您的文件夹。在你的情况下,你要去两个文件夹。
您可能需要重新构建程序,以便将图片存储在试图删除它们的文件下方。
此外,请确保传递正确的文件名字符串以取消链接。如果您不确定,可以回显文件名进行测试。