根据键排列数组

时间:2013-03-22 10:03:31

标签: php arrays

我尝试了什么: - array_merge,函数并将值赋给数组,如我的代码所示。如何动态完成?如何动态地为数组赋值? 这是我的数组: -

Array
(
[data1] => Array
    (
        [0] => 22nd March 
        [1] => 15th March 
        [2] => 22nd March 

   )
[data2] => Array
    (
        [0] => 98 
        [1] => 100 
        [2] => 96
     )

[data3] => Array
    (
        [0] => h 
        [1] => q
        [2] => w
    )
)

Desired output:-
Array
(
[0]=>Array
   (
    [data1]=>22nd March
    [data2]=>98
    [data3]=>h
   )
 [1]=>Array
   (
    [data1]=>15th March
    [data2]=>100
    [data3]=>q
   )
 [2]=>Array
   (
    [data1]=>22nd March
    [data2]=>96
    [data3]=>w
   )

3 个答案:

答案 0 :(得分:1)

您正在寻找的操作称为"转置"。因此,一些搜索导致this answer

function transpose($array) {
    array_unshift($array, null);
    return call_user_func_array('array_map', $array);
}

答案 1 :(得分:1)

function arrange_array($arr) {
  $finalarray = array();
  foreach($arr as $key => $val){
     foreach ($val as $subkey => $subvalue) {
           $finalarray[$subkey][$key] = $subvalue;
        }
  }
  return $finalarray;  
}

答案 2 :(得分:0)

没什么逻辑,你到达这个:

$req_array = array(); 

 foreach($array as $key =>$value)
{
   foreach($value as $subkey=>$subvalue)
    {
    $req_array[$subkey][$key] = $subvalue;
    }
  }

echo "<pre>";
print_r($req_array);
echo "</pre>";