Reputation: 655
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
.
Upvotes: 4
Views: 241
Reputation: 16462
$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]);
Upvotes: 3
Reputation: 18706
$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];
}
}
Upvotes: 1
Reputation: 784998
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;
}
Upvotes: 3