我有2个阵列
$a = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>4);
$b = array('v1'=>1,'v2'=>2,'v3'=>3,'v4'=>5);
如何将它们合并到单个数组中:
Array
(
[v1] => 1
[v2] => 2
[v3] => 3
[v4] => Array
(
[0] => 4
[1] => 5
)
)
我尝试过使用array_merge
& array_merge_recursive
。
答案 0 :(得分:3)
您可以使用此代码:
$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;
}
答案 1 :(得分:3)
$result = array_intersect_assoc($a, $b);
foreach (array_diff_assoc($a, $b) as $k => $v)
$result[$k] = array($v, $b[$k]);
<强>更新强>
anubhava的解决方案很好。它可以像这样简化:
$c = array();
foreach($a as $k => $v)
$c[$k] = $b[$k] == $v ? $v : array($v, $b[$k]);
答案 2 :(得分: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];
}
}