简体   繁体   English

使用php array_merge_recursive时数字键输入错误

[英]Wrong numeric key when using php array_merge_recursive

I am trying to recursively merge two arrays using array_replace_recursive. 我试图使用array_replace_recursive递归合并两个数组。 This is the code: 这是代码:

$col = array();
$new = array_merge_recursive($col, array('table1' => array(1 => true)));
$new = array_merge_recursive($new, array('table1' => array(0 => false)));

The dump of the $new array is $ new数组的转储是

array(1) { ["table1"]=> array(2) { [1]=> bool(true) [2]=> bool(false) } }

What i need is to preserve the numeric keys of the "table1" array. 我需要保留“ table1”数组的数字键。 The expected result should be 预期结果应该是

array(1) { ["table1"]=> array(2) { [0]=> bool(false) [1]=> bool(true) } }

Does anyone have a solution for this? 有人对此有解决方案吗?

You could switch the order of your arguments 您可以切换参数的顺序

$new = array_merge_recursive(array(), array('table1' => array(0 => false)));
$new = array_merge_recursive($new, array('table1' => array(1 => true)));

The problem you're running into is you already created a key so subsequent calls will append to the first element of the array. 您遇到的问题是您已经创建了一个键,因此后续调用将追加到数组的第一个元素。

使用array_replace_recursive而不是array_merge_recursive

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM