按键顺序对多维数组进行排序

问题描述 投票:0回答:1

基本上,我正在构建具有动态输入的html表单输入,例如,在下面的示例中,如果用户要增加unit_type,则用户可以从前端添加新输入并将其发送到存储中

注意:如果用户将添加unit_type,则所有其他键将自动添加。就像如果用户尝试增加unit_type一样,那么unit_address和所有其他输入也会相应增加。

现在我有这样的数组

   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
  ]
]

预期结果

[
  [
     //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'
 ]
]
php arrays for-loop multidimensional-array dynamic-arrays
1个回答
0
投票
循环浏览现有的返回数据并像这样构建新的数组:

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

© www.soinside.com 2019 - 2024. All rights reserved.