我有两个数组,分别是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 ) ) );更多推荐
合并具有共同值的数组
发布评论