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

时间:2014-06-03 04:38:10

标签: php arrays implode

我有一个数组

$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";

我该怎么做?

3 个答案:

答案 0 :(得分:4)

请尝试这个,它使用array_chuck,explode和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;

OutputRed 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;

OutputRed blue, yellow dog, cat fish, mountain

答案 1 :(得分:2)

你绝对需要将字符串分解为数组吗?如果没有,这将是一个更简单的解决方案:

$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

答案 2 :(得分:1)

$output='';
$alternate=false;
foreach($arr as $val) {
   $output.=$val.($alternate==true?', ':' ');
   $alternate=($alternate==false);
}
$output=trim($output);
//$output now is what you want.