Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 带有可选项的多文件上载_Php_Html_Forms_File - Fatal编程技术网

Php 带有可选项的多文件上载

Php 带有可选项的多文件上载,php,html,forms,file,Php,Html,Forms,File,我有一个包含多个输入的表单,如下所示: <div id="users"> <input type="text" name="title[]" required> <input type="file" name="images[]"> <input type="text" name="title[]" require

我有一个包含多个输入的表单,如下所示:

<div id="users">
<input type="text" name="title[]" required>
<input type="file" name="images[]">

<input type="text" name="title[]" required>
<input type="file" name="images[]">

<input type="text" name="title[]" required>
<input type="file" name="images[]">

</div>

<input type="button" value="add new user">
<input type="submit" value="submit">
title  = ["title1","title2","title3"]
images = [image1.jpg,image3.jpg]
user1:{title="title1",image=image1.jpg}
user2:{title="title2",image=null}
user3:{title="title3",image=image3.jpg}
.
.
.
用户数量不是固定的,用户可以通过单击“添加新用户”按钮添加任意数量的标题和图像。因此,“添加新用户”按钮将向users div添加一对输入:

<input type="text" name="title[]" required>
<input type="file" name="images[]">

您可以检查是否为文件设置了特定索引:

var_dump($_POST['title'][0]);
if (isset($_FILES['images']['tmp_name'][0])) {
    var_dump($_FILES['images']['tmp_name'][0]);
}

您所要做的就是处理这两个数组,并检查是否有与每个标题匹配的图像。如果每个标题都没有图像,请将您喜欢的任何内容替换为图像名称

<?php
  if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  
    $output = [];

    foreach( $_POST['title'] as $idx => $title){
      $u = $idx+1;
      $output['user'.$u] = ['title'=>$title, 
                              'images'=> $_POST['images'][$idx] == '' ? 'NULL' : $_POST['images'][$idx]];
    }
    $j = json_encode($output);
    echo $j;
  }

谢谢大家,Pavol Velky在一定程度上是正确的,尽管数组大小小于输入数,但浏览器将为数组设置索引,例如,如果您有两个输入,并且只选择第二个输入,数组将类似于:item:[1:{}](如果选择第一个:item:[{}])您可以通过索引号检查顺序。

不需要硬编码特定索引,浏览器将以任何方式返回数组,但索引正确,PHP中的数组通常从
0
not
1
开始。您是对的。我编辑答案。我不确定是否发送了空文件输入。问题是,如果将image2保留为空,输入将被忽略,并且只有两个文件将发送到服务器ex:[file1,file3],因此我无法识别哪个文件设置为空。如果用户将file1保留为空,那么我又有了一个包含两个项的数组!那是不对的。尝试使用dump$\u FILES变量并查看其结构。我测试它以确保每个图像输入的结构都和预期的一样,即使是空的。数组(1){[“图像”]=>;数组(5){[“名称”]=>;数组(3){[0]=>;字符串(0)“[1]=>;字符串(0)“[2]=>;字符串(0)”}……在我的例子中,如果我从三个可选文件输入中设置一个文件,我会得到一个长度为1的数组。为它们指定名称,
图像[one]
图像[two]
输入的计数是不固定的,因此我无法分配这样的名称。问题是,如果用户将file1设置为空或file2设置为空,则请求将是一个包含1项的数组,不可能知道哪一项设置为空。在您的示例中,如果用户将image1设置为空,而将image2保留为空,则我将再次拥有一个包含1项的数组。在这两种情况下图像[1]=文件,图像[2]=空
{
    "user1":{"title":"asss","images":"NULL"},
    "user2":{"title":"dd","images":"hammer.jpg"}
}