合并具有共同值的数组

编程入门 行业动态 更新时间:2024-10-24 10:25:09
本文介绍了合并具有共同值的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两个数组,分别是arr和arr2.

I have two arrays namely arr and arr2.

var arr=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]; var arr2=[{"month":"January","ip":12},{"month":"June","ip":10}];

是否可以从两个数组上方显示下面的数组?

Is it possible to get array below shown from above two arrays?

result=[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}];

如果我使用array_merge,那么我会得到答案

If i use array_merge then i get answer as

result=[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192},{"month":"January","ip":12},{"month":"June","ip":10}];

推荐答案

想到的第一个函数是 array_merge_recursive(),但是即使将临时关联键分配给子数组,也要结束在新的深子数组中包含多个 January 值.

The first function that comes to mind is array_merge_recursive(), but even if you assign temporary associative keys to the subarrays, you end up with multiple January values in a new deep subarray.

但是不要失望,还有另一个递归函数可以完成这项工作.只要首先分配临时关联键, array_replace_recursive()将成功合并这些多维数组.

But do not despair, there is another recursive function that can do this job. array_replace_recursive() will successfully merge these multidimensional arrays so long as temporary associative keys are assigned first.

这里是一种单行代码,它不使用 foreach()循环或if语句:

Here is a one-liner that doesn't use foreach() loops or if statements:

代码:( 演示)

$arr=json_decode('[{"month":"January","url":1},{"month":"February","url":102},{"month":"March","url":192}]',true); $arr2=json_decode('[{"month":"January","ip":12},{"month":"June","ip":10}]',true); echo json_encode(array_values(array_replace_recursive(array_column($arr,NULL,'month'),array_column($arr2,NULL,'month'))));

输出:

[{"month":"January","url":1,"ip":12},{"month":"February","url":102},{"month":"March","url":192},{"month":"June","ip":10}]

明细:

echo json_encode( // convert back to json array_values( // remove the temp keys (reindex) array_replace_recursive( // effectively merge/replace elements associatively array_column($arr,NULL,'month'), // use month as temp keys for each subarray array_column($arr2,NULL,'month') // use month as temp keys for each subarray ) ) );

更多推荐

合并具有共同值的数组

本文发布于:2023-10-17 10:29:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!