I have a folder, which contains thousands of images for my website products, looking like this:
D25200-1.jpg
D25200-2.jpg
D25200-3.jpg
D25201-1.jpg
D25201-2.jpg
D25201-3.jpg
D25201-4.jpg
Which means, that product D25200
has 3 photos and D25201
has 4 photos.
I want to delete some of the images, but keep the count from 1. For example, if I delete D25201-1.jpg
and D25201-2
, the rest of the images to get renamed as D25201-1.jpg
and D25201-2.jpg
.
This is the code I've created so far, but it only deletes the photos:
<?php
$codes = array(
'D25201' => '1,2'
);
$dirs = array(
dirname(__FILE__) . '/products/',
dirname(__FILE__) . '/products/large/',
dirname(__FILE__) . '/products/medium/',
dirname(__FILE__) . '/products/small/'
);
foreach($codes as $code => $photos) {
$photos = explode(',', $photos);
foreach($photos as $photo) {
foreach($dirs as $dir) {
unlink($dir . $code . '-' . $photo . '.jpg');
}
}
}
?>
I havn't had time to test this but something like this should do it (Or atleast give you a hint at a possible direction the figure the rest out yourself):
$codes = array(
'D25201' => '1,2'
);
$dirs = array(
dirname(__FILE__) . '/products/',
dirname(__FILE__) . '/products/large/',
dirname(__FILE__) . '/products/medium/',
dirname(__FILE__) . '/products/small/'
);
foreach($codes as $code => $photos) {
$photos = explode(',', $photos);
foreach($photos as $photo) {
foreach($dirs as $dir) {
if(unlink($dir . $code . '-' . $photo . '.jpg');){
//if unlink is successfull... loop all images in current dir
$files = scandir($dir);
$c = 0;
foreach($files as $file){
$c++;
//if the name of the image contains the productcode
if(strpos($file,$code) !== false){
//rename the file
rename ($file , $dir . $code . '-' . $c . '.jpg');
}
}
}
}
}
}
There is probably a better way, using less loops, but something like this should work.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加