[英]How to transform array to comma separated words string without using implode()
My array looks like this:我的数组如下所示:
Array
(
[0] => lorem
[1] => ipsum
[2] => dolor
[3] => sit
[4] => amet
)
How to transform this to a string like this with php?如何使用php将其转换为这样的字符串?
$string = 'lorem, ipsum, dolor, sit, amet';
使用 join() - 你可以使用 join,它是 implode 的别名,也更具可读性:
echo join(',',$array);
$str="";
foreach($yourarray as $key=>$value){
$str.=$value.",";
}
rtrim($str, ",");
echo $str;
<?php
$array = array("1" => "lorem",
"2" => "ipsum",
"3" => "dolor",
"4" => "sit",
"5" => "amet"
);
$string = "";
foreach( $array as $key => $value ){
$string.=$value.",";
}
echo $string;
use below solution:使用以下解决方案:
<?php
$array = Array
(
0 => 'lorem',
1 => 'ipsum',
2 => 'dolor',
3 => 'sit',
4 => 'amet',
);
$str = '';
foreach($array as $a){
$str .= $a.', ';
}
echo rtrim($str, ',');
output输出
lorem, ipsum, dolor, sit, amet
using for loop:使用 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, ",");
Use implode function to convert,a string into array.使用 implode 函数将字符串转换为数组。 Please try this,it will give you the output you want
请试试这个,它会给你你想要的输出
<?php
$array = Array
(
0 => 'lorem',
1 => 'ipsum',
2 => 'dolor',
3 => 'sit',
4 => 'amet',
);
$string = implode(",",$array);
echo '$string = '."'".$string."'";
?>
使用 for 循环并将项目连接到字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.