PHP合并两个关联数组

$array 1:-

Array
(
    [Test Stock] => Array
        (
            [intStockCount] => 10
        )

    [CARTON 50 X 50 X 50] => Array
        (
            [intStockCount] => 10
        )
)

$array2:-

Array
(
    [Test Stock] => Array
        (
            [intInvoiceCount] => 20
        )

    [CARTON 50 X 50 X 50] => Array
        (
            [intInvoiceCount] => 30
        )
)

我需要一个不使用循环就将所有元素组合在一起的新数组

Array
(
    [Test Stock] => Array
        (
            [intStockCount] => 10
            [intInvoiceCount] => 20
        )

    [CARTON 50 X 50 X 50] => Array
        (
            [intStockCount] => 10
            [intInvoiceCount] => 30
        )
)

解决方法:

您可以使用array_merge_recursive来完成这项工作.

array_merge_recursive

array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the prevIoUs one. It returns the resulting array.

If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended.

做就是了:

<?PHP
$array1 = array(
    "Test Stock" => array(
        "intStockCount" => 10
    ),
    "CARTON 50 X 50 X 50" =>  array(
        "intStockCount" => 10
    )
);

$array2 = array(
    "Test Stock" => array(
        "intInvoiceCount" => 20
    ),
    "CARTON 50 X 50 X 50" =>  array(
        "intInvoiceCount" => 30
    )
);

$final = array_merge_recursive($array1,$array2);
echo '<pre>';
print_r($final);
echo '</pre>';

/* OUTPUT
Array
(
    [Test Stock] => Array
        (
            [intStockCount] => 10
            [intInvoiceCount] => 20
        )

    [CARTON 50 X 50 X 50] => Array
        (
            [intStockCount] => 10
            [intInvoiceCount] => 30
        )

)
*/

这里要注意的重要一点是,您在两个数组中都使用了相同的字符串键.如PHP文档所述

…the values for these keys are merged together into an array

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...