将数组转换为字符串

4

我有一个字符串数组,需要构建一个由某个字符(如逗号)分隔的值的字符串。

$tags;
6个回答

21

18

有一个简单的函数叫做implode

$string = implode(';', $array);

7
你应该使用 implode 函数。
例如,implode(' ',$tags); 将在数组中的每个项之间放置一个空格。

2
如果您不想使用implode函数,您也可以使用以下函数:
function my_implode($separator,$array){
   $temp = '';


   foreach($array as $key=>$item){
       $temp .=  $item; 
       if($key != sizeof($array)-1){
            $temp .= $separator  ; 
       }
   }//end of the foreach loop

   return $temp;
}//end of the function

$array = array("One", "Two", "Three","Four");


$str = my_implode('-',$array);
echo $str;

0

使用implode

$array_items = ['one','two','three','four']; 
$string_from_array = implode(',', $array_items);

echo $string_from_array;
//output: one,two,three,four

使用join(implode的别名)

$array_items = ['one','two','three','four']; 
$string_from_array = join(',', $array_items);

echo $string_from_array;
//output: one,two,three,four

0

还有一个函数join,它是implode的别名。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接