Home > Back-end >  Laravel how to split array into two based on the key value
Laravel how to split array into two based on the key value

Time:10-06

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"=>"", .. ]

CodePudding user response:

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);
  • Related