通过索引合并两个数组 [英] 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
}
或者您可以将数据放入$ 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屋!