$_FILES array and its silly structure [duplicate]

孤者浪人 提交于 2019-12-10 04:35:28

问题


Possible Duplicate:
How do you loop through $_FILES array?

For some reason arrays really get to me. I can get there in the end, but this $_FILES array seems to be backwards to me.

I want to be able to loop through $_FILES like so:

foreach($_FILES as $file)
{
   echo $file['name'] . "<br>";
   echo $file['type'] . "<br>";
   echo $file['size'] . "<br>";
   echo $file['error'] . "<br>";
}

But obviously with the way its structured you cannot do that. So I have written the following:

echo "<pre>";
                $x=0;
                $file = array();
                foreach($_FILES['attachment']['name'] as $data)
                {   $file[$x]=array(); 
                    array_push($file[$x],$data); $x++;
                }
                $x=0;
                foreach($_FILES['attachment']['type'] as $data)
                    {   array_push($file[$x],$data); $x++;}

                $x=0;
                foreach($_FILES['attachment']['tmp_name'] as $data)
                    {   array_push($file[$x],$data); $x++;}
                $x=0;
                foreach($_FILES['attachment']['error'] as $data)
                    {   array_push($file[$x],$data); $x++;}
                $x=0;
                foreach($_FILES['attachment']['size'] as $data)
                    {   array_push($file[$x],$data); $x++;}
                var_dump($file);
                echo "</pre>";

Which seems very long winded and rediculous but my mind is stuck at the moment as to how to loop through properly the different parts of this array to get it work and loop the way I want it to.

There must be a better way?

Please help!


回答1:


If they all have the same length you can do it like this

for($i = 0; $i < count($_FILES['attachment']['name']); $i++)
{
   echo $_FILES['attachment']['name'][$i] . "<br>";
   echo $_FILES['attachment']['type'][$i] . "<br>";
   echo $_FILES['attachment']['size'][$i] . "<br>";
   echo $_FILES['attachment']['error'][$i] . "<br>";

}



回答2:


From your code, i suppose your <form> inputs look like this:

<input type="file" name="attachment[]">
<input type="file" name="attachment[]">

If you give unique names to the file fields you should get the $_FILES structure you want:

<input type="file" name="attachment0">
<input type="file" name="attachment1">

results in something like this:

array(2) {
  'attachment0' => array(5) {
    'name'     => string(8) "1528.jpg"
    'type'     => string(0) ""
    'tmp_name' => string(0) ""
    'error'    => int(2)
    'size'     => int(0)
  }
  'attachment1' => array(5) {
    'name'     => string(8) "1529.jpg"
    'type'     => string(0) ""
    'tmp_name' => string(0) ""
    'error'    => int(2)
    'size'     => int(0)
  }
}


来源:https://stackoverflow.com/questions/11690570/files-array-and-its-silly-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!