微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐