【问题标题】:Laravel how to split array into two based on the key valueLaravel如何根据键值将数组一分为二
【发布时间】:2021-11-26 14:05:25
【问题描述】:

大家好,我正在开发一个 laravel 项目,该项目要求用户在页面中提交带有文件的数据。用户点击提交时会同时提交多个表单,我在提交时使用formData分隔文件和其他正常输入

  const formData = new FormData();
  for (var key in this.equipments) {
    formData.append('id_'+key, JSON.stringify(this.equipments[key]));
  }
  this.equipments.forEach((item, idx) => {
    formData.append("file_" + idx, item.New_Cert);
  });
  axios
    .post("/equipments/calibration", formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    })

这是我通过 request->all() 在后端得到的输出

请问如何根据键值将此请求数组一分为二? 目前数组结构是这样的

   [
    "id_0" => ".."
    "id_1" => ".."
    ....
    "file_0" =>"..."
    "file_1"=>""...."
    ....
    ]

我可以把它分成两个数组,这样我就有了

  1. id 数组

    [ "id_0"=>"", "id_1"=>"", ... ]

  2. 文件数组

    [ "file_0"=>"", "file_1"=>"", .. ]

【问题讨论】:

    标签: php laravel multipartform-data laravel-8


    【解决方案1】:

    试试这个解决方案:

    使用键值获取索引作为键, 检查子字符串并保存到新数组中

    <?php
    
    $array = [
      "id_0" => "..",
      "id_1" => "..",
      "file_0" =>"...",
      "file_1"=>"....",
    ];
    
    $id_arr = [];
    $file_arr = [];
    
    foreach($array as $key => $value)
    {
      if(substr($key, 0, 3) == "id_")
      {
        $id_arr[$key] = $value; 
      }
      else if(substr($key, 0, 5) == "file_")
      {
        $file_arr[$key] = $value; 
      }
    }
    
    
    var_dump($id_arr);
    var_dump($file_arr);
    

    【讨论】:

      猜你喜欢
      • 2022-01-17
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 1970-01-01
      • 2018-08-17
      相关资源
      最近更新 更多