php 如何在数组中合并2个元素- Laravel

2fjabf4q  于 2023-03-21  发布在  PHP
关注(0)|答案(2)|浏览(150)

我很困惑地将2个元素组合在数组中,这是输出:

array:16 [▼ // app\Http\Controllers\TappingController.php:18
  0 => "-3.6475644"
  1 => "114.8616161"
  2 => "-3.6475625"
  3 => "114.8613661"
  4 => "-3.6475798"
  5 => "114.8604937"
  6 => "-3.6475471"
  7 => "114.8596975"
  8 => "-3.6464274"
  9 => "114.8598053"
  10 => "-3.6449308"
  11 => "114.85987"
  12 => "-3.6439882"
  13 => "114.8599144"
  14 => "-3.6427097"
  15 => "114.8599408"
]

我想要这样的结果:

array:8 [▼ // app\Http\Controllers\TappingController.php:18
  0 => "-3.6475644,114.8616161"
  1 => "-3.6475625,114.8613661"
  2 => "-3.6475798,114.8604937"
  3 => "-3.6475471,114.8596975"
  4 => "-3.6464274,114.8598053"
  5 => "-3.6449308,114.85987"
  6 => "-3.6439882,114.8599144"
  7 => "-3.6427097,114.8599408"
]

怎么会得到这样的结果呢?

mtb9vblg

mtb9vblg1#

你可以通过循环遍历原始数组并将每两个元素连接成一个新数组来实现这一点。下面是一个示例代码片段:

$originalArray = [
    "-3.6475644",
    "114.8616161",
    "-3.6475625",
    "114.8613661",
    "-3.6475798",
    "114.8604937",
    "-3.6475471",
    "114.8596975",
    "-3.6464274",
    "114.8598053",
    "-3.6449308",
    "114.85987",
    "-3.6439882",
    "114.8599144",
    "-3.6427097",
    "114.8599408",
];

$newArray = [];

for ($i = 0; $i < count($originalArray); $i += 2) {
    $newArray[] = $originalArray[$i] . ',' . $originalArray[$i + 1];
}

print_r($newArray);

这将输出:

Array
(
    [0] => -3.6475644,114.8616161
    [1] => -3.6475625,114.8613661
    [2] => -3.6475798,114.8604937
    [3] => -3.6475471,114.8596975
    [4] => -3.6464274,114.8598053
    [5] => -3.6449308,114.85987
    [6] => -3.6439882,114.8599144
    [7] => -3.6427097,114.8599408
)
esbemjvw

esbemjvw2#

你可以使用array_map()函数来合并数组中的两个元素:

$result = array_map(function($a, $b) {
    return $a . ',' . $b;
}, $array[0], $array[1]);

相关问题