php – 按索引合并两个数组

前端之家收集整理的这篇文章主要介绍了php – 按索引合并两个数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
好吧,如果觉得这应该是非常简单并且通过像array_merge()或array_merge_recursive这样的函数来完成,但我无法弄明白.我有两个简单的数组,如下面的(简化)示例.我只是想根据它们的索引将它们合并到一个数组中.

$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 
 )
)

当我尝试使用合并函数合并这些时,我只能得到这个:

$unDesiredResult:

Array ( 
  [0] => Array ( 
        [ID] => 201 
        [latLng] => 45.5234515,-122.39466520000002 
  )
  [2] => Array ( 
        [distance] => 1000 
        [time] => 10 
  )  
  [3] => Array ( 
        [distance] => 1500 
        [time] => 15 
  )
)

我需要循环将第二组推入第一组,还是可以使用现有功能完成?

我不认为有一个功能为你做这个,你将不得不循环.
$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,因此您需要创建第3个数组:

foreach($array1 as $key=>&$val){ // Loop though one array
    $val2 = $array2[$key]; // Get the values from the other array
    $val += $val2; // combine 'em
}

猜你在找的PHP相关文章