php阵列合并&结合

时间:2012-12-24 09:14:55

标签: php arrays

我有三个阵列&我喜欢在一个多维数组中转换它。

$array1=array('Kathy', 'Adam', 'Jenny');
$array2=array('student','teacher','driver');
$array3=array(2, 5, 8);

$mix=array(); 
$mix['name']=array_values( $array1);
$mix['profession']=array_values( $array2);
$mix['SL']=array_values( $array3);

&安培;从这些数组我可以得到低于输出:

Array
(
[name] => Array
    (
        [0] => Kathy
        [1] => Adam
        [2] => Jenny
    )

[profession] => Array
    (
        [0] => student
        [1] => teacher
        [2] => driver
    )

[SL] => Array
    (
        [0] => 2
        [1] => 5
        [2] => 8
    )

   )

现在我想从上面得到以下输出...任何人请帮我怎么做?

     [0]=>Array
      (
         [name] =>  Kathy
         [profession] =>student
         [SL] => 2
    )

    [1]=>Array
    (    
         [name] => Adam
         [profession] =>teacher
         [SL] =>  5
     )

    [2]=>Array
    (
         [name] => Jenny
         [profession] =>driver
         [SL] =>  8
    )

4 个答案:

答案 0 :(得分:5)

您可以使用array_map函数执行此操作:

<?php

$array1 = array('Kathy', 'Adam', 'Jenny');
$array2 = array('student','teacher','driver');
$array3 = array(2, 5, 8); 

$mix = array_map(
    function ($name, $profession, $sl) {
        return array('name' => $name, 'profession' => $profession, 'SL' => $sl);
    },  
    $array1,
    $array2,
    $array3
);

答案 1 :(得分:2)

$array1=array('Kathy', 'Adam', 'Jenny');
$array2=array('student','teacher','driver');
$array3=array(2, 5, 8);
$mix = array();

foreach ($array1 as $index => $val)
{
    $mix[] = array(
    'name' => $val, 
    'profession' => $array2[$index], 
    'SL' => $array3[$index]);
}

答案 2 :(得分:0)

使用此:

  $array1=array('Kathy', 'Adam', 'Jenny');
  $array2=array('student','teacher','driver');
  $array3=array(2, 5, 8);
  $mix=array();

  for($i=0;$i<count($array1);$i++){
         $mix[$i]=array('name'=>$array1[$i],'profession'=>$array2[$i],'SL'=>$array3[$i]);
   }

  print_r($mix);

如果所有数组都具有相同的大小,请使用此选项。

答案 3 :(得分:0)

没问题,你可以使用这段代码:

$array1=array('Kathy', 'Adam', 'Jenny');
$array2=array('student','teacher','driver');
$array3=array(2, 5, 8);

$mix=array();

if (count($array1)==count($array2) && count($array2)==count($array3)){
    $count = count($array1);
    for ($i=0;$i<$count;$i++){
        $mix[] = array(
            'name' => isset($array1[$i]) ? $array1[$i] : '',
            'profession' => isset($array2[$i]) ? $array2[$i] : '',
            'SL' => isset($array3[$i]) ? $array3[$i] : '',
        );
    }
}