0

我正在尝试将上传的文件放入循环中以减少代码。

<input type="file" name="new1[]" accept="image/*">
<input type="file" name="new2[]" accept="audio/*">
<input type="file" name="new3[]" accept="text/*">

在 php 中有这些文件的循环

<?php
 $all=array();
 $all[]=array('new1','Dir_for_1st_type_to_store');
 $all[]=array('new2','Dir for 2nd type');
 $all[]=array('new3','Dir for 3rd type');

 for($i=0;$i<count($all);$i++){
   $newFile=$$all[$i][0]; //that is VAR in VAR trick
   echo $newFile; //that's Ok. Temp files with paths displayed
   echo $newFile_name[$i]; //that's not Ok. No output

 ....................//here is a HUUUUUUGE amount of code, written for 'one file variable'
 }
?>

怎么了?

4

2 回答 2

4

试试这个:

HTML:

<input type="file" name="new1[]" accept="image/*" multiple />
<input type="file" name="new2[]" accept="audio/*" multiple />
<input type="file" name="new3[]" accept="text/*" multiple />

PHP:

$map = Array(
    "new1"=>"Dir_for_1st_type_to_store",
    "new2"=>"Dir for 2nd type",
    "new3"=>"Dir for 3rd type",
);
foreach($map as $k=>$v) {
    $fileArray = $_FILES[$k];
    $keys = array_keys($fileArray["name"]);
    foreach($keys as $key) {
        $newFile = array_map(function($a) use ($key) {return $a[$key];},$fileArray);
        var_dump($newFile); // you should see temp filename and other file info
        var_dump($v); // this should be the target folder
        // do stuff with it
    }
}
于 2013-02-01T18:38:17.633 回答
1

PHP 有一种组织$_FILES数组的愚蠢方式**。这个 HTML 表单:

<input type="file" name="new1[]" accept="image/*">
<input type="file" name="new1[]" accept="image/*">

<input type="file" name="new2[]" accept="audio/*">
<input type="file" name="new2[]" accept="audio/*">

<input type="file" name="new3[]" accept="text/*">
<input type="file" name="new3[]" accept="text/*">

生成类似于以下内容的数组:

// 1st new1 file
$_FILES["new1"]["name"    ][0]
$_FILES["new1"]["type"    ][0]
$_FILES["new1"]["size"    ][0]
$_FILES["new1"]["tmp_name"][0]
$_FILES["new1"]["error"   ][0]
// 2nd new1 file
$_FILES["new1"]["name"    ][1]
$_FILES["new1"]["type"    ][1]
$_FILES["new1"]["size"    ][1]
$_FILES["new1"]["tmp_name"][1]
$_FILES["new1"]["error"   ][1]
// likewise for 1st new2, 2nd new2, 1st new3, 2nd new3

你的代码可以写成:

$all = array();
$all["new1"] = array("Dir for 1st type");
$all["new2"] = array("Dir for 2nd type");
$all["new3"] = array("Dir for 3rd type");

foreach ($all as $key => $conf) {
    for ($i = 0; $i < count($_FILES[$key]["name"]); $i++) {
        if ($_FILES[$key]["error"][$i] === 0) {
            echo $_FILES[$key]["tmp_name"][$i] . " goes to " . $conf[0] . "\n";
            // HUUUUUUGE amount of code goes here
        }
    }
}

** 这只是我的意见。

于 2013-02-01T18:59:40.767 回答