使用name []时在PHP中正确堆叠文件数组

时间:2013-09-09 15:50:32

标签: php multidimensional-array

我有一个动态表单,当我收集数据时,我使用name='samples[]'标记中的input将所有上传的文件放入一个数组中。目前,这会生成一个数组,其中每个文件属性(例如$_FILES['samples']['name'])都是一个数组,依次包含每个文件的相应属性。理想情况下,我希望$_FILES['samples']成为一个数组,其中每个成员都是一个单独的文件,然后每个文件属性将包含一个值,而不是一个数组。我尝试了各种移动括号的组合,但无济于事。

目前的安排:

["samp"]=>
  array(5) {
    ["name"]=>
    array(2) {
      [0]=>
      string(23) "bank account update.pdf"
      [1]=>
      string(15) "teudamichal.pdf"
    }
    ["type"]=>
    array(2) {
      [0]=>
      string(15) "application/pdf"
      [1]=>
      string(15) "application/pdf"
    }
    ["tmp_name"]=>
    array(2) {
      [0]=>
      string(14) "/tmp/phpIjWlii"
      [1]=>
      string(14) "/tmp/phptgVldB"
    }
    ["error"]=>
    array(2) {
      [0]=>
      int(0)
      [1]=>
      int(0)
    }
    ["size"]=>
    array(2) {
      [0]=>
      int(30547)
      [1]=>
      int(556583)
    }
  }

我想要的是什么:

["samp"]=>
  array(2){
    [0]=> 
      array(5) {
        ["name"]=> string(23) "bank account update.pdf"
        ["type"]=> string(15) "application/pdf"
        ["tmp_name"]=> string(14) "/tmp/phpIjWlii"
        ["error"]=> int(0)
        ["size"]=> int(30547)
      }}
    [1]=> 
      array(5) {
        ["name"]=> string(23) "michal.pdf"
        ["type"]=> string(15) "application/pdf"
        ["tmp_name"]=> string(14) "/tmp/phpIjWlij"
        ["error"]=> int(0)
        ["size"]=> int(30547)
      }}
    }

1 个答案:

答案 0 :(得分:3)

我不能相信这一点,因为它直接来自$_FILES上的PHP手册页 - http://php.net/manual/en/reserved.variables.files.php

阅读文档可以解决这个问题。


使用输入名称作为数组时重新排序$ _FILES数组的一个很好的技巧是:

<?php
function diverse_array($vector) {
    $result = array();
    foreach($vector as $key1 => $value1)
        foreach($value1 as $key2 => $value2)
            $result[$key2][$key1] = $value2;
    return $result;
}
?>

会改变这个:

array(1) {
    ["upload"]=>array(2) {
        ["name"]=>array(2) {
            [0]=>string(9)"file0.txt"
            [1]=>string(9)"file1.txt"
        }
        ["type"]=>array(2) {
            [0]=>string(10)"text/plain"
            [1]=>string(10)"text/html"
        }
    }
}

成:

array(1) {
    ["upload"]=>array(2) {
        [0]=>array(2) {
            ["name"]=>string(9)"file0.txt"
            ["type"]=>string(10)"text/plain"
        },
        [1]=>array(2) {
            ["name"]=>string(9)"file1.txt"
            ["type"]=>string(10)"text/html"
        }
    }
}

只是这样做:

<?php $upload = diverse_array($_FILES["upload"]); ?>