找到 foreach() 循环的最后一个条目,内爆不起作用
我循环遍历数组来打印文章名称:
<?php
if ($articles) {
foreach($articles as $article) {
echo $article->name.", ";
} // end foreach article
} // end if has articles
?>
这显然会产生类似的内容
Apple, Banana, Mango,
但我正在寻找:
Apple, Banana, Mango
我尝试了一些像这样的内爆语句:
<?php
if ($articles) {
foreach($articles as $article) {
echo implode(", ", $article->name);
} // end foreach article
} // end if has articles
?>
或者
<?php
if ($articles) {
echo implode(", ", $articles->article->name);
} // end if has articles
?>
这些都不适合我。怎样才能做对呢?感谢您的提示!
I loop through my array to print the articles names:
<?php
if ($articles) {
foreach($articles as $article) {
echo $article->name.", ";
} // end foreach article
} // end if has articles
?>
This will obviously produce something like
Apple, Banana, Mango,
But I am looking for:
Apple, Banana, Mango
I tried some implode statement like this:
<?php
if ($articles) {
foreach($articles as $article) {
echo implode(", ", $article->name);
} // end foreach article
} // end if has articles
?>
or
<?php
if ($articles) {
echo implode(", ", $articles->article->name);
} // end if has articles
?>
None of these are working for me. How can do it right? Thanks for hints!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
foreach
将文章名称添加到数组中,然后使用implode()
该名称数组。You can use
foreach
to add the article names to an array, thenimplode()
that array of names.检查你的第一次循环迭代要容易得多,在文本之前写下逗号,并在第一次迭代时保留这个逗号:
另一种(在我的选项中更漂亮)可能性是覆盖你的 _toSting() 方法文章类:
简单地
echo implode(", ",$articles)
it's much more easy to check for your first loop-iteration, wrte the comma before your text and leave this comma aout on the first iteration:
another (more beautiful in my optionion) possibility would be to override the _toSting()-method of your article-class:
and simply
echo implode(", ",$articles)
这是做你想做的事情的更好方法:
It is better way to do what you want:
PHP 有很多优秀的数组函数,这就是其中之一。
或者
我也非常喜欢上面对 __toString 函数的响应,但我想展示这些数组函数,因为我认为它们经常没有得到充分利用,有利于或不必要的 foreach 循环。
PHP has a lot of good array functions, and this screams for one of them.
OR
I really like the above response with the __toString function also, but I wanted to show these array functions because i think they are often underused in favor or unnecessary foreach loops.
您可以使用修剪功能删除最后一个逗号和空格。这是最简单的方法..
You can remove last comma and space by using trim function. It is the easiest way..