将数组合并在一起

时间:2015-12-26 04:29:38

标签: php arrays

我有这两个数组,我想将它们合并为一个。使用第二个数组中0,1的重复值。下面是我希望它看起来如何的一个例子。我希望有人可以提供帮助。

Array(
    [201500001] => Array
        (
            [0] => 1003123603
            [1] => 3062226597
        )

    [201500002] => Array
        (
            [0] => 3067005512
        )

)
Array(
    [1127893457] => Array
        (
            [0] => 1003123603
            [1] => 
        )

    [1127893467] => Array
        (
            [0] => 1003133106
            [1] => 3067005512
        )

    [1127893443] => Array
        (
            [0] => 1004146393
            [1] => 3062226597
        )

    [1127893246] => Array
        (
            [0] => 1003154423
            [1] => 5149282937
        )

)

预期产出:

   Array(
    [1127893457] => Array
        (
            [0] => 1003123603
            [1] => 
            [2] => 201500001
        )

    [1127893467] => Array
        (
            [0] => 1003133106
            [1] => 3067005512
            [2] => 201500002
        )

    [1127893443] => Array
        (
            [0] => 1004146393
            [1] => 3062226597
            [2] => 201500001
        )

    [1127893246] => Array
        (
            [0] => 1003154423
            [1] => 5149282937
            [2] => 
        )

)

2 个答案:

答案 0 :(得分:0)

将一个或多个数组的元素合并在一起,以便将一个值的值附加到前一个数组的末尾。它返回结果数组。

<?php
$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);
print_r($result);
?>

答案 1 :(得分:0)

我将各种数组重写为有效数组。除此之外,我认为您正在寻找的是使用array_intersect。这对我有用:

$source = array(
    201500001 => array(
        0 => 1003123603,
        1 => 3062226597
    ),
    201500002 => array(
        0 => 3067005512
    )
);

$target = array(
    1127893457 => array(
        0 => 1003123603
    ),
    1127893467 => array(
        0 => 1003133106,
        1 => 3067005512
    ),
    1127893443 => array(
        0 => 1004146393,
        1 => 3062226597
    ),
    1127893246 => array(
        0 => 1003154423,
        1 => 5149282937
    )
);

$expected = array(
    1127893457 => array(
        0 => 1003123603,
        2 => 201500001
    ),
    1127893467 => array(
        0 => 1003133106,
        1 => 3067005512,
        2 => 201500002
    ),
    1127893443 => array(
        0 => 1004146393,
        1 => 3062226597,
        2 => 201500001
    ),
    1127893246 => array(
        0 => 1003154423,
        1 => 5149282937
    )
);

$newArray = [];

foreach ($target as $targetKey => $targetValue) {
    foreach ($source as $sourceKey => $sourceValue) {
        if (array_intersect($sourceValue, $targetValue)) {
            $targetValue[2] = $sourceKey;
        }
        $newArray[$targetKey] = $targetValue;
    }
}

echo ($newArray === $expected) ? "Match!" : "Miss." . PHP_EOL;