在PHP中有两个数组:
$x = array( "a" => "0123", "b" => "1234", "c" => "0123");
$y = array( "a" => "3210", "b" => "1234", "d" => "0123");
我希望将结果放在一个这样的数组中:
// right
Array
(
[a] => 0123
[b] => 1234
[c] => 0123
[a] => 3210
[d] => 0123
)
我尝试使用array_merge($ x,$ y):
// wrong
Array
(
[a] => 3210
[b] => 1234
[c] => 0123
)
它发生因为有旧数据库和新数据库,我从两个数据库获得两个值。如果来自两个数据库的值完全相等,那么它只需要像这样的值:
[b] => 1234
请问PHP代码中有一些解决方案吗?
答案 0 :(得分:2)
因为你不能使用array_merge_recursive获得相同的密钥。 它将为相同的密钥创建多维数组。
$ar1 = array("color" => array("favorite" => "red"), 5);
$ar2 = array(10, "color" => array("favorite" => "green", "blue"));
$result = array_merge_recursive($ar1, $ar2);
[color] => Array
(
[favorite] => Array
(
[0] => red
[1] => green
)
[0] => blue
)
[0] => 5
[1] => 10
答案 1 :(得分:0)
数组不能有重复的密钥,如果保持密钥对你不重要,那么以下工作正常:
此代码直接来自PHP array_merge文档。
<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
输出:
Array
(
[color] => green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)