PHP循环,改变最后一项?
这实际上可能是一个 css 问题,但我希望不是,因为我希望它能在 IE 中工作。
我有以下循环:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
应该输出
项目,项目,项目,项目,
唯一的事情是......我不想在最后一个项目之后有逗号。有没有办法在循环内做到这一点?
This might actually be a css question but I'm hoping not because I'd like this to work in IE.
I have the following loop:
<?php
if ($category)
{
foreach($category as $item)
{
echo $item['name'];
echo ", ";
}
} ?>
Which should output
item, item, item, item,
The only thing is...I'd like to NOT have a comma after the last item. Is there any way to do this within a loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
为了保持代码原样,您可以添加一个计数器,并跳过最后一个。
或者你可以做得更多、更多、更快:
Well to keep your code how it is, you could add a counter, and skip the last one.
Or you can do it much, much, quicker:
不要立即回显,而是将输出保存到可以修剪的变量中。
Don't echo immediately but save your output into a variable that you can trim.
implode
解决方案是最简单的,但您要求一个循环。此方法避免在循环中放置额外的条件,因此应该更有效。基本上,您不是对最后一个项目执行不同的操作,而是对第一个项目执行不同的操作。编辑:意识到你想要 $item['name'] 而不仅仅是 $item 后:
The
implode
solution is the simplest, but you asked for a loop. This method avoids putting an extra conditional in the loop, and therefore should be somewhat more efficient. Basically, instead of doing something different for the last item, you do something different for the first item.EDIT: After realizing you want $item['name'] instead of just $item:
尽管
foreach
很可爱,......
for
有时是必要的。As lovely as
foreach
is,......
for
is sometimes necessary.假设
$category
是一个数组,您可以使用 implode 得到你想要的:编辑: 错过了 $categories['name'] 部分,这应该有效:
Assuming
$category
is an array, you can use implode to get what you want:Edit: Missed the $categories['name'] part, this should work:
“最后一个逗号”问题的标准解决方案是将项目放入数组中,然后将其内爆:
如果您想要更通用,您还可以编写一个函数,从每个子数组中挑选(“抽取”)特定字段:
然后就
The standard solution to the "last comma" problem is to put items into an array and then implode it:
If you want this more generic, you can also write a function that picks ("plucks") a specific field out of each subarray:
and then just
或者你可以检查最后一个键:
Or you could check for the last key:
还有另一个选择:
And another option: