I’m trying to get an image gallery management removal process working in PHP. I’ve been stumbling on how I could update the list order so they stay in the same order after the removal.
I have an associative array ($images) where the key is the same as the ‘order’ value this number defines the placement in the gallery. I also have a list of the order numbers which should be removed this removes each image by identifying it with the order number.
$images format
array(28) {
[1]=>
array(5) {
["gallery_id"]=>
string(2) "71"
["property_id"]=>
string(1) "3"
["picture"]=>
string(17) "imgname.jpg"
["order"]=>
string(1) "1"
["alt_text"]=>
string(14) "discription"
}
[2]=>
array(5) {
["gallery_id"]=>
string(2) "83"
["property_id"]=>
string(1) "3"
["picture"]=>
string(17) "imgname.jpg"
["order"]=>
string(1) "2"
["alt_text"]=>
string(14) "discription"
}
So on... how ever large the list might be.
List of images to remove
$removedImgs
array(2) {
[0]=> string(1) "1"
[1]=> string(1) "3"
}
The above shows images 1 and 3 will be removed from the gallery
Current: 1 2 3 4 5 6 ...
Removal: 2 4 5 6
| | | |
Reordering: 1 2 3 4
The actual removal code
// Loop though with each image and remove the ones posted from the list
foreach ($_POST['orderID'] as $removeImg)
{
// Store each removed images order id
$removedImgs[] = $removeImg;
// If we're removing images create a list of the image paths to
// unlink the files later.
if (isset($images[$removeImg]))
{
$unlinkList[] = $imgPath . $images[$removeImg]['picture'];
$unlinkList[] = $imgPath . 'thumbs/thumb' . $images[$removeImg]['picture'];
}
// $images should only contain the ones that we haven't removed.
unset($images[$removeImg]);
// Update the image order
foreach ($images as $key => &$img)
{
if ($key > $removeImg)
{
(int)$img['order']--;
}
}
var_dump($images);
echo "\n\n==========\n\n";
}
If you have control over when the images are removed, you’d have a much easier time updating the orders at that time.