0

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

2
  • 2
    don't you mean array('a' => array('1', '9'), ... ? Commented Oct 28, 2009 at 18:09
  • @SilentGhost, Probably. I don't have much experience with multiple nested levels of associative arrays. But your format should do the job too. Commented Oct 28, 2009 at 18:11

2 Answers 2

3
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]);
}
Sign up to request clarification or add additional context in comments.

3 Comments

your second form will generate what he was looking for. This assumes that both associative arrays will have the same keys.
true, it never been intended to be more sophisticated. It's fairly easy to do produce more general solution, not sure OP needs it.
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
0
$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.
*/

2 Comments

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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.