PHP 为每一项添加逗号,但最后一项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5440537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:25:19  来源:igfitidea点击:

PHP Add comma to every item but last one

phpcsvfor-loop

提问by giodamelio

I have a loop like

我有一个循环

foreach ($_GET as $name => $value) {
    echo "$value\n";
}

And I want to add a comma in between each item so it ends up like this.

我想在每个项目之间添加一个逗号,所以它最终是这样的。

var1, var2, var3

Since I am using foreachI have no way to tell what iteration number I am on.

由于我正在使用,foreach我无法知道我在使用什么迭代次数。

How could I do that?

我怎么能那样做?

采纳答案by giodamelio

Sorry I did not state my question properly. The awnser that worked for me is

抱歉,我没有正确说明我的问题。为我工作的 awnser 是

implode(', ', $_GET);

Thanks, giodamelio

谢谢,乔达梅利奥

回答by Yanick Rochon

Just build your output with your foreachand then implode that array and output the result :

只需使用您的输出构建您的输出,foreach然后内爆该数组并输出结果:

$out = array();
foreach ($_GET as $name => $value) {
    array_push($out, "$name: $value");
}
echo implode(', ', $out);

回答by Richard Rodriguez

Like this:

像这样:

$total = count($_GET);
$i=0;
foreach ($_GET as $name => $value) {
    $i++;
    echo "$name: $value";
    if ($i != $total) echo', ';
}

Explained: you find the total count of all values by count(). When running the foreach() loop, you count the iterations. Inside the loop you tell it to echo ', ' when the iteration isn't last (isn't equal to total count of all values).

解释:您可以通过 count() 找到所有值的总数。运行 foreach() 循环时,您计算迭代次数。在循环内,您告诉它在迭代未结束时回显 ', ' (不等于所有值的总数)。

回答by u476945

$comma_separated = implode(", ", $_GET);

echo $comma_separated;

you can use implode and achieve that

你可以使用内爆并实现

回答by Brent

You could also do it this way:

你也可以这样做:

$output = '';
foreach ($_GET as $name => $value) {
    $output = $output."$name: $value, ";
}
$output = substr($output, 0, -2);

Which just makes one huge string that you can output. Different methods for different styles, really.

这只是制作一个可以输出的巨大字符串。不同的风格,不同的方法,真的。

回答by DA.

I'd typically do something like this (pseudo code):

我通常会做这样的事情(伪代码):

myVar

for... {
    myVar = i + ","
}

myVar = trimOffLastCharacter(myVar)

echo myVar