PHP 中关联数组的数组合并
我如何在关联数组上进行 array_merge,如下所示:
Array 1:
$options = array (
"1567" => "test",
"1853" => "test1",
);
Array 2:
$option = array (
"none" => "N/A"
);
所以我需要 array_merge 这两个,但是当我这样做时,我得到了这个(在调试中):
Array
(
[none] => N/A
[0] => test
[1] => test1
)
How can i do an array_merge on an associative array, like so:
Array 1:
$options = array (
"1567" => "test",
"1853" => "test1",
);
Array 2:
$option = array (
"none" => "N/A"
);
So i need to array_merge these two but when i do i get this (in debug):
Array
(
[none] => N/A
[0] => test
[1] => test1
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
尝试使用:
$finalArray = $options + $option。参见http://codepad.org/BJ0HVtac
只需检查重复键的行为,我没有对此进行测试。对于唯一的键,它效果很好。
try using :
$finalArray = $options + $option .see http://codepad.org/BJ0HVtac
Just check the behaviour for duplicate keys, I did not test this. For unique keys, it works great.
只需使用
$options + $option
!输出:
但是当发生按键碰撞时要小心。这是PHP手册所说的:
第一个数组中的键将被保留。 如果两个数组中都存在数组键,则将使用第一个数组中的元素,并忽略第二个数组中匹配键的元素。
Just use
$options + $option
!outputs:
But be careful when there is a key collision. Here is what the PHP manual says:
The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored.
参考:http://www.php.net/manual/en/function.array-merge.php#90136
Reference: http://www.php.net/manual/en/function.array-merge.php#90136
当 array_merge 不起作用时,只需
根据哪个数组具有更高优先级执行或切换两个 foreach 循环
when
array_merge
doesn't work, then simply door switch the two
foreach
loops depending on which array has higher priority此代码可用于递归合并:
This code could be used for recursive merge:
如果数组具有相同的键,则使用 array_merge_recursive() 。
array_merge_recursive() 不会覆盖,它只是将值作为数组。
If arrays having same keys then use
array_merge_recursive()
The
array_merge_recursive()
wont overwrite, it just makes the value as an array.