首页 / PHP / PHP合并两个关联数组
PHP合并两个关联数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了PHP合并两个关联数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1738字,纯文字阅读大概需要3分钟。
内容图文
![PHP合并两个关联数组](/upload/InfoBanner/zyjiaocheng/681/7b206ab7058c4a63b1417c3a2b0a4cb9.jpg)
$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() 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
内容总结
以上是互联网集市为您收集整理的PHP合并两个关联数组全部内容,希望文章能够帮你解决PHP合并两个关联数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。