Thursday, 30 August 2018

foreach () not & ldquo; for eaching & rdquo; elements in the PHP array

If I do this, it works:

$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);
}

Problem being is that the above code is nested meaning it runs a new MySQL query for each time it runs the unlink function so I made the below code to make it not do that:
$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);
}

I get this error in return:
Warning: unlink( "../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png") [function.unlink]: No such file or directory

it's obviously not going to find the "../../users/biondizzle/photos/pic_3387677.png" , "../../users/biondizzle/photos/pic_1581185.png"directory because that's 2 separate directories running at the same time so the foreach() isn't "foreaching".
Any way to get the unlink() to run separately for each directory i have listed in the array, I thought I would get it to work by adding the commas and quotations with the implode()? Thanks a bunch, hope I explained it well enough -Mike

I think this is what you want to do:
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);
}

You will notice I have removed the $the_pics_raw_3 .= " \"../../". implode("\" , \"../../" ,$the_pics_raw_2)."\""; line as it was converting the array into a string, which was making it impossible to then foreach over.

0 comments:

Post a Comment