當上傳多個檔案時,$_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'];
print '檔案類型:' . $file['type'];
print '檔案大小:' . $file['size'];
}
}
?>