按索引合并两个数组 [英] Merging two arrays by index
问题描述
好吧,如果觉得这应该很简单,并且可以通过像 array_merge()
或 array_merge_recursive
这样的函数来完成,但我不太明白.我有两个简单的数组,其结构类似于下面的(简化的)示例.我只是想根据它们的索引将它们合并到一个数组中.
Okay, if feel like this should be really simple and accomplished by a function like array_merge()
or array_merge_recursive
, but I can't quite figure it out. I have two simple arrays structured like the (simplified) example below. I simply want to merge them into one array based on their index.
$array 1:
Array (
[0] => Array (
[ID] => 201
[latLng] => 45.5234515, -122.6762071
)
[1] => Array (
[ID] => 199
[latLng] => 37.7931446, -122.39466520000002
)
)
等等……
$array2 :
Array (
[0] => Array (
[distance] => 1000
[time] => 10
)
[1] => Array (
[distance] => 1500
[time] => 15
)
)
$desiredResult :
Array (
[0] => Array (
[ID] => 201
[latLng] => 45.5234515, -122.6762071
[distance] => 1000
[time] => 10
)
[1] => Array (
[ID] => 199
[latLng] => 37.7931446, -122.39466520000002
[distance] => 1500
[time] => 15
)
)
当我尝试使用合并函数合并这些时,我只能得到这个:
When I try to merge these using merge functions, I can only get this:
$unDesiredResult:
Array (
[0] => Array (
[ID] => 201
[latLng] => 45.5234515, -122.6762071
)
[1] => Array (
[ID] => 199
[latLng] => 37.7931446, -122.39466520000002
)
[2] => Array (
[distance] => 1000
[time] => 10
)
[3] => Array (
[distance] => 1500
[time] => 15
)
)
我是否需要循环将第二个集合推入第一个集合,还是可以使用现有函数来完成?
Do I need to loop through to push the second set into the first, or can this be done with an existing function?
推荐答案
我认为没有一个函数可以为您执行此操作,您将不得不循环.
I don't think there is a function to do this for you, you're gonna have to loop.
$result = array();
foreach($array1 as $key=>$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other array
$result[$key] = $val + $val2; // combine 'em
}
或者你可以将数据push到$array1中,所以你需要制作第三个数组:
Or you can push the data into $array1, so you need to make a 3rd array:
foreach($array1 as $key=>&$val){ // Loop though one array
$val2 = $array2[$key]; // Get the values from the other array
$val += $val2; // combine 'em
}
这篇关于按索引合并两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!