tags:

views:

62

answers:

2

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' => array("3", "7")
);

Thanks

+3  A: 
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]);
}
SilentGhost
your second form will generate what he was looking for.This assumes that both associative arrays will have the same keys.
Ben Reisner
true, it never been intended to be more sophisticated. It's fairly easy to do produce more general solution, not sure OP needs it.
SilentGhost
Thanks to both of you :) I tested, and it looks like Ben's answer fits it better, but I still have a small bug with the blanks. I'll open another question
drummer
A: 
$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.
*/
Ben Reisner
SilentGhost had the better one if it is just 2 arrays and they have the same keys. If the keys may vary or you need to scale from 2 arrays then this is closer to what you need.
Ben Reisner
Good point. I think they probably may vary. For example 1 array could have a b d (no c), but the other a b c (no d). In this case, I will need it as a b c d but with blanks inserted for whatever is missing for one or the other. You say this will do better than the other?
drummer