合并两个数组

时间:2013-08-27 03:21:36

标签: php arrays merge

我有两个数组

Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [color] => 0
                )

            [1] => Array
                (
                    [color] => 1
                )

        )

)

Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [kaka] => 0
                )

            [1] => Array
                (
                    [kaka] => 1
                )

        )

)

我想合并该数组,因此输出为

Array
(
    [rows] => Array
        (
            [0] => Array
                (
                    [color] => 0,
                    [kaka] => 0
                )

            [1] => Array
                (
                    [color] => 1,
                    [kaka] => 0
                )
        )
)

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这个

$arr1 = array('row' => array(
                '0' => array ('color' => 0),
                '1' => array ('color' => 1)
              ));
$arr2 = array('row' => array(
                '0' => array ('kaka' => 0, 'dada' => 2),
                '1' => array ('kaka' => 1, 'tata' => 2),
                '2' => array ('kaka' => 2)
              ));

function merge($arr1, $arr2) {
    $result = $arr1;
    foreach($arr2['row'] as $key => $value) {
        foreach($value as $vkey => $vvalue) {
            $result['row'][$key][$vkey] = $vvalue;
        }
    }

    return $result;
}

$merge = merge($arr1, $arr2);
var_dump($merge);

输出

array (size=1)
  'row' => 
    array (size=3)
      0 => 
        array (size=3)
          'color' => int 0
          'kaka' => int 0
          'dada' => int 2
      1 => 
        array (size=3)
          'color' => int 1
          'kaka' => int 1
          'tata' => int 2
      2 => 
        array (size=1)
          'kaka' => int 2