上传多个文件时,$_FILES 变量以以下形式创建
数组
(
[name] => 数组
(
[0] => foo.txt
[1] => bar.txt
)
[type] => 数组
(
[0] => text/plain
[1] => text/plain
)
[tmp_name] => 数组
(
[0] => /tmp/phpYzdqkD
[1] => /tmp/phpeEwEWG
)
[error] => 数组
(
[0] => 0
[1] => 0
)
[size] => 数组
(
[0] => 123
[1] => 456
)
)
我发现如果上传的文件数组采用以下形式,代码会更简洁一些
数组
(
[0] => 数组
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => 数组
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
我编写了一个快速函数,可以将 $_FILES 数组转换为更简洁(在我看来)的数组。
<?php
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
?>
现在我可以执行以下操作
<?php
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
?>