每两个元素用逗号连接数组


Join array with a comma every two elements

我有一个数组

$str = $query->get_title(); //Red blue yellow dog cat fish mountain
$arr = explode(" ",$str);
//output of $arr
Array
(
    [0] => Red 
    [1] => blue 
    [2] => yellow 
    [3] => dog 
    [4] => cat 
    [5] => fish 
    [6] => mountain
)

现在我想将上面的数组与每两个单词的,连接起来。预期结果如下

$result = "Red blue, yellow dog, cat fish, mountain";

我该怎么做呢?

请试试这个,它使用array_chuck, explosion和implode。

<?php
$str = "Red blue yellow dog cat fish mountain";
$result = implode(', ', array_map(function($arr) {
    return implode(' ', $arr);
}, array_chunk(explode(' ', $str), 2)));
echo $result;

输出:Red blue, yellow dog, cat fish, mountain


如果你不喜欢嵌套的方法,另一个使用forloop的方法。

<?php
$str = "Red blue yellow dog cat fish mountain";
$words = explode(' ', $str);
foreach ($words as $index => &$word)
    if ($index % 2)
        $word .= ',';
$result = implode(' ', $words);
echo $result;

输出:Red blue, yellow dog, cat fish, mountain

你一定要把字符串变成一个数组吗?如果没有,这将是一个更简单的解决方案:

$str = $query->get_title(); //Red blue yellow dog cat fish mountain
$result = preg_replace('/('s.*?)'s/',"$1, ",$str);//Red blue, yellow dog, cat fish, mountain
$output='';
$alternate=false;
foreach($arr as $val) {
   $output.=$val.($alternate==true?', ':' ');
   $alternate=($alternate==false);
}
$output=trim($output);
//$output now is what you want.