PHP递归合并 [英] php recursive merge

查看:153
本文介绍了PHP递归合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些不同的方式合并一些数组和我用array_merge_recursive。
然而,有我需要改变的东西,我不知道怎么办。
下面是从php.net报价

I need to merge some arrays in some different way and I use array_merge_recursive. However there is something that I need to change and I don't know how. Here is quote from php.net

如果,然而,阵列具有相同的数字键时,后面的值
  将不会覆盖原来的值,但将被追加。

If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

我想这个价值,而不是要追加,我要不要在你已经明白这个新array.Hope追加精确值。

I want this value, NOT to be appended, I want not to append exact values in the new array.Hope you've understood this.

例如:

$array = array(
   'some'  => array(
       'other'    => 'key',
   ),
);

$array2 = array();
$array2['some']['other'] = 'key2';

如果我用array_merge_recursive这将导致这样的:

If I use array_merge_recursive It will result this:

Array (
    [some] => Array
        (
            [other] => Array
                (
                    [0] => key
                    [1] => key2
                )
        ) )

我想如果匹配相同的结果,而不是追加it.Yes我知道,你会说,然后用array_merge,但它不工作也很好。
如果我用这个:

I want if it matches the same result, not to append it.Yes I know, you would say, then use array_merge, but it doesn't work well, too. If I use this:

$array = array(
   'some'  => array(
       'other'    => 'key',
   ),
);

$array2 = array();
$array2['some']['other2'] = 'key2';

print_r(array_merge($array, $array2));

这将删除$阵列[某些] [其他]从列表中,只留下$阵列[某些] [其它2]。我不知道哪个更好,因为没有人令它变得更好。

It will remove $array[some][other] from the list and leave only $array[some][other2].I don't know which is better, since no one makes it better.

推荐答案

试试这个

<?php
function mymerge(&$a,$b){ //$a will be result. $a will be edited. It's to avoid a lot of copying in recursion
    foreach($b as $child=>$value){
        if(isset($a[$child])){ 
            if(is_array($a[$child]) && is_array($value)){ //merge if they are both arrays
                mymerge($a[$child],$value);
            }
            //else ignore, you can add your own logic, i.e when 1 of them is array
        }
        else
            $a[$child]=$value; //add if not exists
    }

    //return $a;
}

这篇关于PHP递归合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆