我正在尝试创建一个简单的上传器类来使用上传多个图像。我需要从uploadFiles方法返回文件信息,并在另一个方法(uploadGalleryImages)中使用它。但是,如果我使用return $ result,则在第一个文件上传后,foreach循环停止。如果我没有退回并只使用print_r($ result),我可以上传所有文件并在chrome的网络标签中查看该对象。这是我的简化代码:
public function uploadGalleryImages() {
$upload_image = $this->uploadFiles($_FILES['image']);
}
private function reArrayFiles($files) {
$array = array();
$file_count = count($files['name']);
$file_keys = array_keys($files);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$array[$i][$key] = $files[$key][$i];
}
}
return $array;
}
private function uploadFiles($files = array()) {
$upload_dir = IMAGE_UPLOAD_DIR;
$thumb_dir = $upload_dir . 'thumbnails/';
$file_array = $this->reArrayFiles($files);
foreach ($file_array as $file) {
$base_name = pathinfo($file['name'], PATHINFO_FILENAME);
$extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$counter = 1;
while(file_exists($upload_dir . $file['name'])) {
$file['name'] = $base_name . $counter . '.' . $extension;
$counter++;
};
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
//print_r($result);
return $result; // Stops after first file uploaded
} else {
return false;
}
}
}
答案 0 :(得分:3)
将所有图片对象存储在数组中并将其返回。简单的例子:
$pics = [];
foreach ($file_array as $file) {
if (move_uploaded_file($file['tmp_name'], $upload_dir . $file['name'])) {
$result = new \stdClass();
$result->file_name = $file['name'];
$result->extension = $extension;
$pics[] = $result;
}
}
return $pics;