开发者

Merging multiple associative arrays in PHP

I'm not quite sure how to do this. Let's say I have 2 associative arrays

$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'c' => "7");

How could I possibly produce an "add-up" array as below

$arr1 = array(
  array('a', "1", "9"),
  array('b', "2", "8"),
  array('c', "3", "7")
);

I'm not sure if the above syntax is correct. If it's not, then an add-up that looks like below will do too

$arr1 = array(
  'a' => array("1", "9"),
  'b' => array("2", "8"),
  'c' =&开发者_C百科gt; array("3", "7")
);

Thanks


foreach($arr1 as $k=>$v) {
    $new[$k] = array($v, $arr2[$k]);
}

Is what I think you want. But if I'm mistaken, then you could do:

foreach($arr1 as $k=>$v) {
    $new[] = array($k, $v, $arr2[$k]);
}


$arr1 = array('a' => "1", 'b' => "2", 'c' => "3");
$arr2 = array('a' => "9", 'b' => "8", 'c' => "7");

$summ=array();
foreach(array($arr1,$arr2) as $arr){
    $keys=array_keys($arr);
    foreach($keys as $key){
        if(isset($summ[$key]))
            $summ[$key][]=$arr[$key];
        else $summ[$key]=array($arr[$key];
    }
}
/*
This will have made:
$sum = array(  
    'a' => array("1", "9"),  
    'b' => array("2", "8"),  
    'c' => array("3", "7")
);

I leave it up to you to now reduce this one more step to match your desired output.
*/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜