0

Hello guys I am working on a laravel project that requires user to submit data with files in a page. There are multiple form will be submitted at once when user click submit, I am using formData to separate the files and other normal input when submit

  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",
      },
    })

This is the output I getting in my backend with request->all() enter image description here

May I ask how can I separate this request array into two based on the key value? Currently the array structure is like

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

can I divide it into two array so that I will have

  1. id array

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

  2. file array

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

0

1 Answer 1

1

Try this solution:

using key value get index as key, check substring and save into new arrays

<?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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.