1

我有三个数组,我喜欢将它转换为一个多维数组。

$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

4 回答 4

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
);
于 2012-12-24T09:22:42.733 回答
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]);
}
于 2012-12-24T09:25:05.657 回答
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);

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

于 2012-12-24T09:20:39.863 回答
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] : '',
        );
    }
}
于 2012-12-24T09:25:02.987 回答