使用key作为唯一元素将数组添加到另一个数组

时间:2018-03-25 11:52:00

标签: php

我有两个数组,第一个是这样的:

Array
(
    [4301] => Array
        (
            [business_unit_id] => 2
            [no_of_invoices] => 1
            [invoice_status_query] => 1
        )

    [4501] => Array
        (
            [business_unit_id] => 1
            [no_of_invoices] => 2
            [invoice_status_query] => 0
        )

)

和另一个这样的数组:

Array
(
    [4301] => Array
        (
            [business_unit_id] => 2
            [PO_to_be_Approved] => 0
        )

    [4501] => Array
        (
            [business_unit_id] => 1
            [PO_to_be_Approved] => 0
        )

)

那么我如何在第一个和第二个数组中获得下面这个array的内容?:

Array
(
    [4301] => Array
        (   
            [business_unit_id] => 2
            [no_of_invoices] => 1
            [invoice_status_query] => 1
            [business_unit_id] => 2
            [PO_to_be_Approved] => 0
        )

    [4501] => Array
        (
            [business_unit_id] => 1
            [no_of_invoices] => 2
            [invoice_status_query] => 0
            [business_unit_id] => 1
            [PO_to_be_Approved] => 0
        )

)

我知道array_merge函数会创建4个数组元素。但是我需要创建一个新的数组,并将Key作为一个独特的元素。

2 个答案:

答案 0 :(得分:0)

您可以循环遍历第二个数组并将元素添加到第一个数组

foreach($array2 as $key => $value) {
    $array1[$key] = $value;
}

您不能拥有重复的密钥,因此array2中的business_unit_id将覆盖array1中的任何值

答案 1 :(得分:0)

如果[business_unit_id] => 1的密钥对于4501和4301这两个密钥始终相同,则可以使用array_replace_recursive

$array1 = [
    "4301" => [
        "business_unit_id" => 2,
        "no_of_invoices" => 1,
        "invoice_status_query" => 1
    ],
    "4501" => [
        "business_unit_id" => 1,
        "no_of_invoices" => 2,
        "invoice_status_query" => 0
    ]
];

$array2 = [
    "4301" => [
        "business_unit_id" => 2,
        "PO_to_be_Approved" => 0
    ],
    "4501" => [
        "business_unit_id" => 1,
        "PO_to_be_Approved" => 0
    ]
];

$result = array_replace_recursive($array1, $array2);
print_r($result);

如果您希望将[business_unit_id] => 1的两个键合并到一个数组中,您可以使用array_merge_recursive的2个foreach循环:

foreach ($array1 as $key1 => &$value1) {
    foreach ($array2 as $key2 => $value2) {
        if ($key1 === $key2) {
            $value1 = array_merge_recursive($value1, $value2);
        }
    }
}

Demo