1

我有具有相同键的数组,如下所示:

Array1(
    [00] => green
    [10] => red
    [20] => yellow
)

Array2(
    [00] => avocado
    [10] => apple
    [20] => banana
)

我要这个:

Array_result(
    [00] => Array(
            [0] => green
            [1] => avocado
        )

    [10] => Array(
            [0] => red
            [1] => apple
        )

    [20] => Array(
            [0] => yellow
            [1] => banana
        ))

或者[0]、[1]、[2],我不介意key,我尝试了array_merge,但它不能正常工作。

编辑:我不知道为什么,但是 array_merge_recursive 打印了这个:

Array
(
    [00] => Array
        (
            [0] => green
            [1] => avocado
        )

    [0] => red
    [1] => apple
    [2] => yellow
    [3] => banana
)
4

2 回答 2

4

您正在寻找array_merge_recursive而不是array_merge.

<?php
$A = Array(00 => "green", 10 => "red", 20 => "yellow");
$B = Array(00 => "avocado", 10 => "apple", 20 => "banana");

$result = array_merge_recursive($A, $B);

print_r($result);?>

看到它在行动

于 2013-03-09T17:15:46.033 回答
0

试试看:

function merge($arr){
$n = array();
if(!empty($arr)){
foreach($arr as $a){
if(!empty($a)){
foreach($a as $k => $v){
$n[$k][] = $v;
}}}}
return $n;
}

// use
$a = array('00' => 'green', '10' => 'red', '20' => 'yellow');
$b = array('00' => 'avocado', '10' => 'apple', '20' => 'apple');
print_r(merge(array($a, $b)));
于 2013-03-09T17:17:20.750 回答