如何迭代上传的图像文件

时间:2017-04-17 09:03:56

标签: php arrays loops zend-framework image-uploading

我想使用foreach()将图像文件移动到文件夹中并打印imageupload名称,tmp_name等。我正在研究zend。

输入数组:

 Array
(
    [imageUpload] => Array
        (
            [name] => P_20170224_134956_BF.jpg
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\phpBCB0.tmp
            [error] => 0
            [size] => 1057039
        )

    [imageUpload1] => Array
        (
            [name] => P_20170308_135054_BF.jpg
            [type] => image/jpeg
            [tmp_name] => C:\xampp\tmp\phpBCD0.tmp
            [error] => 0
            [size] => 1365444
        )

    [imageUpload2] => Array
        (
            [name] => 
            [type] => 
            [tmp_name] => 
            [error] => 4
            [size] => 0
        )

)

代码:

$data = array_merge_recursive(
    $request->getPost()->toArray(),
    $request->getFiles()->toArray()
);
// echo'<pre>';print_r($data); 

$array = array_slice($data, 2);  
print_r($array); 
foreach($array as $files)
{ 
    foreach ($files as $file) {
        print_r($files); 
        $destination  = "public/img/".$file['name']; 
        $file_name    = $file['tmp_name'];
        move_uploaded_file($file_name,$destination);
        $data = __DIR__.('/../../../../../public/img/').$file['name'];
    }
}

print_r(),错误:

 Array
    (
        [name] => P_20170224_134956_BF.jpg
        [type] => image/jpeg
        [tmp_name] => C:\xampp\tmp\phpBCB0.tmp
        [error] => 0
        [size] => 1057039
    )
    <br />
    <b>Warning</b>:  Illegal string offset 'name' in <b>C:\xampp\htdocs\3Dklik\module\Photos\src\Photos\Controller\PhotosController.php</b> on line <b>84</b><br />
    <br />
    <b>Warning</b>:  Illegal string offset 'tmp_name' in <b>C:\xampp\htdocs\3Dklik\module\Photos\src\Photos\Controller\PhotosController.php</b> on line <b>85</b><br />
    <br />
    <b>Warning</b>:  Illegal string offset 'name' in <b>C:\xampp\htdocs\3Dklik\module\Photos\src\Photos\Controller\PhotosController.php</b> on line <b>87</b><br />
    Array
    (
        [name] => P_20170224_134956_BF.jpg
        [type] => image/jpeg
        [tmp_name] => C:\xampp\tmp\phpBCB0.tmp
        [error] => 0
        [size] => 1057039
    )

1 个答案:

答案 0 :(得分:1)

对于这种情况,您不需要两个foreach。您的$files是一个关联数组:

foreach($array as $files)
{ 
    $destination  = "public/img/".$files['name']; 
    $file_name    = $files['tmp_name'];
    move_uploaded_file($file_name,$destination);
    $data = __DIR__.('/../../../../../public/img/').$files['name'];
}

如果你使用foreach作为$files,那么它仍会深入你的内部关联数组,你不能使用键。