Laravel 4 - 在上传之前获取文件输入数组中图像的第一张图像


Laravel 4 - Get first image of images in file input array before uploading

我有这个文件输入:

<input type="file" name="images[]" accept="image/*" multiple />

在我的控制器中,我以这种方式上传它们:

 $x = 0;
 foreach(Input::file('images') as $file) {
                    $filename = $x.'.'.$file->guessClientExtension();
                    //dest, name
                    if (!file_exists($thepath)) {
                        mkdir($thepath, 0777, true);
                    }
                    $uploadflag = $file->move($thepath,$filename);
                    $is_main = ($x==0) ? true : NULL; //Know who's first img
                    $img_submit = DB::table('images')->insert(array(
                        'image_id'          => $filename,
                        'is_main'           => $is_main
                    ));
                    if($uploadflag) {
                        $uploadedfiles[] = $filename;
                    }
                $x++;
 }

有一个插件,如果我对我得到的表单进行print_r,它会按照我想要的方式对它们进行排序:

Array (
[title] => 
[images] => Array
    (
        [0] => 2.png
        [1] => 1.png
        [2] => 3.png
        [3] => 4.png
        [4] => 5.png
    )
[submit] => Submit
)

您可以注意到,名为 2.png(我将其排序为第一个)的图像按预期被容纳在数组的位置 [0]。但是当我尝试上传它时,我将变量 $is_main 设置为另一个图像。如何在阵列位置 [0] 中识别为主图像?

我尝试使用 $x 进行迭代,以便当 foreach 循环中的 $x 为 0 时,我将第一个图像设置为主图像,但看起来在此过程中数组变得"失望"

编辑:如果你至少能告诉我如何在PHP中获取数组中的第一个图像,我很容易知道如何使用Laravel:-)

使用 reset()

$files = Input::file('images');
foreach($files  as $file):
        $filename = $x.'.'.$file->guessClientExtension();
        # Destination, Name
        if (!file_exists($thepath))
            mkdir($thepath, 0777, true);
        $uploadflag = $file->move($thepath,$filename);
        # reset() files to see if current file is the first one
        $is_main = ($file == reset($files)) ? true : NULL;
        $img_submit = DB::table('images')->insert([
            'image_id' => $filename,
            'is_main'  => $is_main
        ]);
        if($uploadflag) 
            $uploadedfiles[] = $filename;
endforeach;