如何在不使用implode()的情况下将数组转换为逗号分隔的单词字符串

时间:2016-06-06 11:01:03

标签: php arrays

我的数组看起来像这样:

Array
(
    [0] => lorem
    [1] => ipsum
    [2] => dolor
    [3] => sit
    [4] => amet
)

如何使用php将其转换为这样的字符串?

$string = 'lorem, ipsum, dolor, sit, amet';

7 个答案:

答案 0 :(得分:2)

使用join() - 你可以使用join,它是implode的别名,也更具可读性:

echo join(',',$array);

答案 1 :(得分:1)

$str="";
foreach($yourarray as $key=>$value){
 $str.=$value.",";
}
rtrim($str, ",");
echo $str;

答案 2 :(得分:1)

<?php

$array = array("1" => "lorem",  
              "2" => "ipsum",
              "3"  => "dolor", 
              "4" => "sit",
              "5" => "amet"
              );



$string = "";       

foreach( $array as $key => $value ){
     $string.=$value.",";
}

echo $string;

答案 3 :(得分:1)

使用以下解决方案:

<?php
$array = Array
        (
            0 => 'lorem',
            1 => 'ipsum',
            2 => 'dolor',
            3 => 'sit',
            4 => 'amet',
        );

$str = '';

foreach($array as $a){
$str .= $a.', ';
}

echo rtrim($str, ',');

<强>输出

lorem, ipsum, dolor, sit, amet

答案 4 :(得分:1)

使用for循环:

$array = [
    0 => 'lorem',
    1 => 'ipsum',
    2 => 'dolor',
    3 => 'sit',
    4 => 'amet',
];

$counter = count($array)-1;
$string = '';

 for ($i=0; $i<=$counter; $i++) {
      $string .= $array[$i].', ';
 }

 echo rtrim($string, ",");

答案 5 :(得分:1)

使用implode函数将字符串转换为数组。 请试试这个,它会给你想要的输出

<?php
    $array = Array
        (
            0 => 'lorem',
            1 => 'ipsum',
            2 => 'dolor',
            3 => 'sit',
            4 => 'amet',
        );
	$string = implode(",",$array);
	echo '$string = '."'".$string."'";
?>

答案 6 :(得分:0)

使用for循环并将项连接到字符串。