0

我有这个文件夹d:/data/pics,其中的图片名为1101-a.jpg, 1101-b.jpg,1102-a.jpg1102-b.jpg。图片 a 和 b 的编号总是相同 - 请注意,此 a 和 b 仅表示“数字”部分之后的文本。但对于每个数字,总是有 2 个结果。

我有一个带有“pics”表的 MySQL 数据库。它有列'id'、'number'、'title1'和'title2'。“数字”列已经有 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);

为了尽可能简化问题,我写了简短的内容。

4

2 回答 2

1

我会做这样的事情:

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

.....
}
于 2015-04-20T23:20:47.363 回答
0

两个循环解决方案是 imo 的方式。如果您在列上设置唯一索引number(无论如何您都应该这样做),则可以进行高效的多行更新。你可以使用 MySQLON 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
}
于 2015-04-21T16:00:11.193 回答