合并两个多维数组但仅保留关联键

时间:2013-12-10 15:01:36

标签: php arrays multidimensional-array

我想以递归方式合并两个数组,保留关联键,但替换其他键。我尝试使用is_numeric()进行密钥检查,但更换密钥“10”和“11”。

示例数组:

数组1:

$arr1['assoc']='foobar';
$arr1[]='test index';
$arr1[][]=array(3,4);
$arr1['10']['test10'][]=array(0,1);
$arr1['11']['test11']=45;
$arr1['multiarray'][]=array(0,1);

ARRAY2:

$arr2[]=1;
$arr2[][]=2;
$arr2['assoc']='test passed';
$arr2['10']['test10'][]=array(0,2);
$arr2['11']['test11']=array(4,5);
$arr2['multiarray'][]=array(0,2);

如何合并它们(通用功能):

array(
    'assoc' => 'test passed',
    0 => 'test index',
    1 => array(
        0 => array(
            0 => 3,
            1 => 4,
        ),
    ),
    10 => array(
        'test10' => array (
            0 => array(
                0 => 0,
                1 => 1,
            ),
            1 => array(
                0 => 0,
                1 => 2,
            ),
        ),
    ),
    11 => array(
        'test11' => array (
            1 => 4,
            2 => 5,
        ),
    ),
    'multiarray' => array(
        0 => array(
            0 => 0,
            1 => 1,
        ),
        1 => array(
            0 => 0,
            0 => 2,
        ),
    ),
    2 => 1,
    3 => array(
        0 => 2,
    ),
)

保留按键的顺序并不重要。

[编辑]解决方案:

function array_max_index_key($arr) {
    $prev = -1;
    if(is_array($arr)) {
        $keys = array_keys($arr);
        foreach($keys as $k => $key) {
            if(is_numeric($key)) {
                if($key == $prev+1) {
                    $prev=$key;
                } else break;
            }
        }
    }
    return $prev;
}

function justfortesting($a1, $a2) {
    $res=$a1;
    $max_key=array_max_index_key($res);
    if(is_array($a1)) {
        foreach ($a2 as $k => $v) {
            if(is_numeric($k) && $k<=$max_key) {
                $max_key++;
                $res[$max_key]=$v;
            } elseif (is_array($v)) {
                $res[$k]=justfortesting($a1[$k], $v);
            } else {
                $res[$k]=$v;
            }
        }
    } else {
        $res=$a2;
    }
    return $res;
}

$arr3=justfortesting($arr1, $arr2);

1 个答案:

答案 0 :(得分:0)

检查is_string()而不是is_numeric()

编辑:

当你要求

is_numeric($key)

检查

is_numeric($key) and !is_string($key)