4

I have 2 arrays

$a = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>4);

$b = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>5);

How do I merge them to a single array like this :

Array
(
    [v1] => 1
    [v2] => 2
    [v3] => 3
    [v4] => Array
        (
            [0] => 4
            [1] => 5
        )
)

I have tried using array_merge & array_merge_recursive.

3
  • 2
    I don't think there's any built-in command that does what you want in a shot... Commented May 25, 2012 at 8:23
  • I am not looking for one either, I am just looking for the shortest way possible. Commented May 25, 2012 at 8:26
  • oh ok, try Samy's solution then :) Commented May 25, 2012 at 8:27

3 Answers 3

3

You can use this code:

$a = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>4);
$b = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>5);
$c = array();
foreach($a as $m => $n) {
   if (($b[$m] != $n))
      $c[$m] = array($n, $b[$m]);
   else
      $c[$m] = $n;
}
Sign up to request clarification or add additional context in comments.

Comments

3
$result = array_intersect_assoc($a, $b);

foreach (array_diff_assoc($a, $b) as $k => $v)
  $result[$k] = array($v, $b[$k]);

Update:
anubhava's solution is good. It can be simplified like this:

$c = array();
foreach($a as $k => $v) 
  $c[$k] = $b[$k] == $v ? $v : array($v, $b[$k]);

Comments

1
$a = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>4);
$b = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>5);
$results = array();

foreach ($a as $key=>$elem) {
  $results[$key][] = $elem;
  if (!in_array($b[$key], $results[$key])) {
    $results[$key][] = $b[$key];
  }
}

2 Comments

Yeah sorry, didn't notice that.
still not, see @anubhava's solution

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.