将数组中的lat / long列表转换为lat / long的assoc数组

时间:2018-04-01 16:18:52

标签: php arrays associative-array

使用PHP,

我想转过这样的话:

Array
(
[0] => -27.61797
[1] => 153.31181
[2] => -27.61801
[3] => 153.31183
[4] => -27.61806
[5] => 153.31188
[6] => -27.61824
[7] => 153.31217
[8] => -27.61826
[9] => 153.31246
[10] => -27.61783
[11] => 153.31324
)     

分为:

Array
(
[0]
   [lat] => -27.61797
   [long] => 153.31181
[1]
   [lat] => -27.61801
   [long] => 153.31183
[2]
   [lat] => -27.61806
   [long] => 153.31188
[3]    
   [lat] => -27.61824
   [long] => 153.31217
[4]
   [lat] => -27.61826
   [long] => 153.31246
[5]    
   [lat] => -27.61783
   [long] => 153.31324
)

这是必需的,所以我可以将lat / long列表传递给映射API,这样我就可以在iOS和Android应用程序中显示路径。

3 个答案:

答案 0 :(得分:0)

假设数组$ myArray包含lat,lng序列 你可以使用步骤2的for循环来构建你需要的$ newArray

  $numCoords  = count($myArray)/2
  for ($i = 0; $i < $numCoords; $i++ ){
    $newArray[$i]['lat'] = $myArray[$i*2]; 
    $newArray[$i]['long'] = $myArray[($i*2)+1]; 
  }

答案 1 :(得分:0)

一个简单的:

for($i = 0; $i < count($your_array); $i += 2) {
    $new_array[] = ['lat' => $your_array[$i], 'long' => $your_array[$i + 1]];
}

复杂的一个:

$keys = ['lat', 'long'];
$new_array = array_map(function($v) use ($keys) { return array_combine($keys, $v); }, array_chunk($your_array, 2));

答案 2 :(得分:0)

使用array_chunk()

执行此操作的方法之一
<?php
$array = [-27.61797,153.31181,-27.61801,153.31183,-27.61806,153.31188,-27.61824,153.31217,-27.61826,153.31246,-27.61783,153.31324];
$chunked  = array_chunk($array,2);
foreach($chunked as $k=>$v){
    $final[$k]['lat'] = $v[0];
    $final[$k]['long'] = $v[1];
}
print '<pre>';
print_r($final);
print '</pre>';
?>

DEMO: https://eval.in/981915