如何为上传的文件使用“变量变量”? [关闭]

I'm trying to put uploaded files into cycle to reduce code.

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

And in php there's cycle for these files

<?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'
 }
?>

What's wrong?

Try this instead:

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
    }
}

PHP has a silly way** of organizing the $_FILES array. This HTML form:

<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/*">

Produces an array similar to:

// 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

Your code could be written as:

$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] . "
";
            // HUUUUUUGE amount of code goes here
        }
    }
}

** That is just my opinion.