如何组合两个多维数组与显示重复键或重复,必须添加值

时间:2013-07-26 01:54:55

标签: php arrays multidimensional-array

我有主数组键a1和a2。

$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));

我希望我的输出

'a1'=>array(
    'gen'=>200
    'gen2'=>300
    'gen'=>300
 ),
'a2'=>array(
    'gen2'=>100
    'gen3' =>600
    'gen3' =>200
)

'a1'=>array(
    'gen'=>500
    'gen2'=>300
)
'a2'=>array(
    'gen2'=>100
    'gen3'=>800
)

我已经尝试过这段代码,但还不够,它没有显示副本,如果它显示了重复键值的总和,那就更好了

<?php
$array1 = array(a1=>array(200,300,300), a2=>array(100,600,200));
$array2 = array(a1=>array('gen','gen2','gen'), a2=>array('gen2','gen3','gen3'));
$result = array();
foreach($array1 as $k => $v) {
    $result[$k] = array_combine($array2[$k], $v);
}
print_r($result);
?>

非常感谢你的帮助

1 个答案:

答案 0 :(得分:0)

$array1 = array(
    'a1' => array(200,300,300),
    'a2' => array(100,600,200));
$array2 = array(
    'a1' => array('gen','gen2','gen'),
    'a2' => array('gen2','gen3','gen3'));
$result = array('a1' => array(), 'a2' => array());
foreach($array2 as $k => $v) {
    foreach ($v as $k2 => $v2){
        if (array_key_exists($v2, $result[$k])){
            $result[$k][$v2] += $array1[$k][$k2];
        } else {
            $result[$k][$v2] = $array1[$k][$k2];
        }
    }
}

输出:

Array
(
    [a1] => Array
        (
            [gen] => 500
            [gen2] => 300
        )
    [a2] => Array
        (
            [gen2] => 100
            [gen3] => 800
        )
)