Laravel 如何根据键值将数组一分为二

Laravel how to split array into two based on the key value

大家好,我正在做一个 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

$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);