递归合并数组PHP [英] Merging arrays recursively PHP
问题描述
我正在使用此函数两个递归合并数组:
I am using this function two merge recursively arrays:
function array_merge_recursive_distinct(array &$array1, array &$array2) {
$merged = $array1;
foreach($array2 as $key => &$value) {
if(is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
要使用此功能,我需要执行以下步骤:
For using this function I am doing the following steps:
- 声明一个空数组$ outArray = array();
- 在while循环中收集所需的信息
- 在while循环中,我调用array_merge_recursive_distinct函数以递归方式填充空数组
但是,最终数组仅包含在上一个while循环中收集到的最后一个信息。我试图找到一种解决方案,但直到现在我还没有成功。我究竟做错了什么?
递归函数在while循环中获取所有信息(我已经在递归函数中打印了输入数组),但似乎它一遍又一遍地覆盖了合并后的数组。However the final array contains only the last information it was gathered during the last while loop. I have tried to find a solution but I haven't succeed until now. What Am I doing wrong? The recursive function takes all the info during the while loops (I have printed the input arrays in the recursive function) but it seems like it overwrites the merged array over and over again.
谢谢
推荐答案
也许这样很方便。 / p>
Perhaps something like this might be handy.
function array_merge_recursive_distinct(array &$array1, array &$array2) { $merged = array_merge($array1,$array2); asort($merged); $merged = array_values(array_unique($merged)); return $merged; } $array1 = []; $array2 = [1,2,3,4,5]; print_r(array_merge_recursive_distinct($array1,$array2)); $array1 = [1,2,3,6,12,19]; $array2 = [1,2,3,4,5]; print_r(array_merge_recursive_distinct($array1,$array2)); // output Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 [6] => 12 [7] => 19 )
在 PHP沙箱
这篇关于递归合并数组PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!