foreach()不是数组PHP中的“for eaching”项

时间:2012-04-16 12:21:00

标签: php mysql arrays

如果我这样做,它可以工作:

$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
$cell_pictures = mysql_fetch_array($data_array2);
foreach($cell_pictures as $pics_being_deleted) 
{
unlink($pics_being_deleted);
}

问题在于上面的代码是嵌套的,这意味着它每次运行unlink函数时都运行一个新的MySQL查询,所以我做了下面的代码,使它不能这样做:

$the_pics_raw_2 = array();
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
while($cell_pictures = mysql_fetch_array($data_array2))
{
$the_pics_raw = $cell_pictures['pic_loc'];
$the_pics_raw_2[] = $the_pics_raw;
}

$the_pics_raw_3 .= " \"../../". implode("\" , \"../../" ,$the_pics_raw_2)."\"";
$the_pics = array($the_pics_raw_3);

foreach($the_pics as $pics_being_deleted) 
{
unlink($pics_being_deleted);
}

我得到了这个错误:

Warning: unlink( "../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png") [function.unlink]: No such file or directory

显然不会找到"../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png"目录,因为这是同时运行的2个独立目录,因此foreach()不是“预告”。

如果让unlink()为我在数组中列出的每个目录单独运行,我想我会通过在implode()中添加逗号和引号来实现它吗? 非常感谢,希望我解释得很好 -Mike

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要做的事情:

while($cell_pictures = mysql_fetch_array($data_array2)) {
    $the_pics_raw = $cell_pictures['pic_loc'];
    $the_pics[] = "../../" . $the_pics_raw;
}

foreach($the_pics as $pics_being_deleted) {
    unlink($pics_being_deleted);
}

您会注意到我删除了$the_pics_raw_3 .= " \"../../". implode("\" , \"../../" ,$the_pics_raw_2)."\"";行,因为它正在将数组转换为字符串,这使得无法再foreach结束。

答案 1 :(得分:0)

使用此代码:

$the_pics_raw = array();
$data_array2 = mysql_query("SELECT pic_loc FROM pictures WHERE user_id = '".$id."'");
while($cell_pictures = mysql_fetch_array($data_array2))
{
array_push($the_pics_raw,"../../".$cell_pictures['pic_loc']);
}

foreach($the_pics as $the_pics_raw) 
{
unlink($pics_being_deleted);
}