如何合并数组

时间:2014-06-11 07:45:06

标签: php arrays

我有两个阵列,比如

Array1
(
    [0] => 1
    [1] => 2
    [2] => 3
)
Array2
(
    [0] => a
    [1] => b
    [2] => c
)
i want make 
Array3 Like
(
    [0] => ([0]=>1 [1]=>a)
    [1] => ([0]=>2 [1]=>b)
    [2] => ([0]=>3 [1]=>c)
)

2 个答案:

答案 0 :(得分:2)

这绝对不是最漂亮的方法,但由于你没有提供任何尝试过的代码,我怀疑是否有人想在这里打扰这个问题:

注意:正如评论中所述,您必须确保这两个数组的长度相同并自行排序。

$one = array(
    '1',
    '2',
    '3'
);

$two = array(
    'a',
    'b',
    'c'
);

$derp = array();

foreach($one as $key => $val) {
    $derp[] = array(
        $val,
        $two[$key]
    );
}
?>

返回

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => a
        )

    [1] => Array
        (
            [0] => 2
            [1] => b
        )

    [2] => Array
        (
            [0] => 3
            [1] => c
        )

)

答案 1 :(得分:1)

使用SPL' MultipleIterator

$arr1 = [1, 2, 3];
$arr2 = ['a', 'b', 'c'];

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($arr1));
$mi->attachIterator(new ArrayIterator($arr2));
$result = array();
foreach($mi as $details) {
    $result[] = $details;
}
var_dump($result);