【问题标题】:Sort the Multi Dimensional array in key sequence按键顺序对多维数组进行排序
【发布时间】:2026-02-23 10:35:01
【问题描述】:

基本上,我正在构建具有动态输入的 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】:

    遍历现有的返回数据并构建新数组,如下所示:

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

    【讨论】: