Search code examples
phparraysfor-loopmultidimensional-arraydynamic-arrays

Sort the Multi Dimensional array in key sequence


Basically, I am building html form inputs that have dynamic inputs For example In below example if user want to increase the unit_type then user can add the new input from front end and send it to store

Note: If user will add the unit_type then all others keys will automatically added. Like if user try to increase the unit_type then unit_address and all other inputs increase accordingly.

Right Now I have the array like this

   array:7 [
  "unit_type" => array:2 [
    0 => null
    1 => null
  ]
  "unit_address" => array:2 [
    0 => null
    1 => null
  ]
  "unit_phone" => array:2 [
    0 => null
    1 => null
  ]
  "fax" => array:2 [
    0 => null
    1 => null
  ]
  "installed_capacity" => array:2 [
    0 => null
    1 => null
  ]
  "production_capacity" => array:2 [
    0 => null
    1 => null
  ]
  "unit_email" => array:2 [
    0 => null
    1 => null
  ]
]

Expected Result

[
  [
     //Here all keys contain the first values of all arrays
    'unit_type'=>'first_value',
    'unit_address'=>'first_value',
    'unit_phone'=>'first_value',
    'fax'=>'first_value',
    'installed_capacity'=>'first_value',
    'production_capacity'=>'first_value',
    'unit_email'=>'first_value'
  ],

  [
    //Here all keys contain the second values of all arrays
   'unit_type'=>'second_value',
   'unit_address'=>'second_value',
   'unit_phone'=>'second_value',
   'fax'=>'second_value',
   'installed_capacity'=>'second_value',
   'production_capacity'=>'second_value',
   'unit_email'=>'second_value'
 ]
]

Solution

  • Loop through the existing return data and build the new array like so:

    $input_array = []; //your data received from the front end
    $return_array = []; //structured data return
    
    foreach($input_array as $field => $fieldData){
    
        foreach ($fieldData as $key => $data){
    
            $return_array[$key][$field] = $data;
        }
    }