我有这个文件夹d:/data/pics
,里面有名为1101-a.jpg
、1101-b.jpg
、1102-a.jpg
、1102-b.jpg
等的图片。 图片 a 和 b 总是相同的数字 - 请注意,这 a 和 b 只是"数字-"部分之后文本的表示。 但是对于每个数字,总是有 2 个结果。
我有一个带有表格"图片"的MySQL数据库。它有列"id","数字","标题1"和"标题2"。"数字"列已经有 1101、1102、1103 等。
我需要从目录中查找所有图片,从它们的名称中取出数字,在我的 MySQL 表中查找相同的数字并将适当的图片名称插入数据库。每个数字都有两张照片。
现在,我知道如何从目录中获取名称,但是我无法将其插入数据库,因为我有两张相同数字的图片,之后我需要与mySQL中的同一行配对。
$directory = opendir("d:/data/images");
$image_format = array("jpg, jpeg, png");
$image_names = array();
while ($file = readdir ($directory)) {
if(in_array(substr(strtolower($file), strrpos($file,".") + 1),$image_format))
{
array_push($image_names,$file);
}
foreach ($image_names as $row) {
//HERE I NEED THE NUMBER IN PIC'S NAME EXTRACTED AS A VALUE FOR EACH PIC:
$pic_number = "$_GET INTEGER FROM IMAGE_NAMES (or $row)" ;
// this i don't know.
$id = $_GET($row['id']);
$number = $_GET($row['number']);
//NOW HERE I NEED THAT $pic_number FROM image_names ABOVE... and then
$sql = "INSERT INTO images (title1, title2) VALUES ($row) WHERE $number = $pic_number;";
mysql_query($sql);
}
}
closedir($directory);
我写了很短的没有逃避,以尽可能简化问题。
我会做这样的事情:
$images = glob("d:/data/images/*-a.{jpg,png,jpeg}", GLOB_BRACE));
foreach($images as $img){
$path_parts = pathinfo($img);
$img = $path_parts['basename'];
$ext = $path_parts['extension'];
$imge = explode('-',$img);
$pic_number = $imge[0];
$file1 = $pic_number."-a.".$ext;
$file2 = $pic_number."-b.".$ext;
.....
}
两个循环解决方案是 imo 的出路。如果在列上设置唯一索引,则可以number
多行更新(无论如何都应该这样做)。然后你可以使用MySQL ON DUPLICATE KEY UPDATE
子句。在使用以下代码之前,请确保number
列上具有唯一索引(唯一id
是不够的):
$img_files = glob("files/*.{jpg,JPG,png,PNG,jpeg,JPEG}", GLOB_BRACE);
$data = array();
foreach ($img_files as $img_file) {
$filename = basename($img_file);
$split_filename = explode('-', $filename, 2);
$number_prefix = (int) $split_filename[0];
$data[$number_prefix][] = $filename;
}
// assuming 0 can't be prefix number $data[0] represents invalid file (without number prefix) - not needed aparently
// unset($data[0]);
$insert_values = '';
foreach ($data as $number => $row) {
$title1 = $row[0];
$title2 = isset($row[1]) ? $row[1] : ''; // empty string in case there's no second file
$insert_values .= "('$number','$title1','$title2'),";
}
$sql = 'INSERT INTO images (number, title1, title2) VALUES ' . substr($insert_values, 0, -1) . '
ON DUPLICATE KEY UPDATE title1 = VALUE(title1), title2 = VALUE(title2)';
//... run query
如果没有索引UPDATE
查询很容易在第二个循环中构建(有数字和两个文件名)。
编辑:循环UPDATE
版本:
//... $insert_values not needed
foreach ($data as $number => $row) {
$title1 = $row[0];
$title2 = isset($row[1]) ? $row[1] : ''; // empty string in case there's no second file
$sql = "UPDATE images SET title1 = '$title1', title2 = '$title2' WHERE number = $number";
// ... execute query
}