在 foreach 中用逗号打印

发布于 2024-12-14 06:46:26 字数 500 浏览 3 评论 0原文

可能的重复:
删除 PHP 中的最后一个逗号?

所以我有以下代码:

<?php
 foreach ($movie->Genres as $genre):
?>
<a href="some_dinamic_link"><?=$genre->name?></a>, 
<?php
endforeach;
?>

这会给我以下内容:动作、戏剧、犯罪,但我不需要最后一个逗号分隔符 - 所以我的问题是避免该逗号的最佳方法是什么?

诗。 如果这很重要的话,我的页面上有 4 个像这样的循环 - 针对演员、导演等。

Possible Duplicate:
Removing last comma in PHP?

So I have the following code:

<?php
 foreach ($movie->Genres as $genre):
?>
<a href="some_dinamic_link"><?=$genre->name?></a>, 
<?php
endforeach;
?>

And this will give me the following: Action, Drama, Crime, but I don't need this last comma separator - so my question is what would be the best way to avoid that comma ?

Ps.
If that matters I have 4 loops like this one on my page - for actors, directors, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

飘过的浮云 2024-12-21 06:46:26

将 A 标签写入数组并加入项目。

<?php
 $items = array();
 foreach ($movie->Genres as $genre):
  $items[] = '<a href="some_dinamic_link">' . $genre->name . '</a>';
 endforeach;
 echo join(', ', $items);
?>

Write you A-tags to an array and join the items.

<?php
 $items = array();
 foreach ($movie->Genres as $genre):
  $items[] = '<a href="some_dinamic_link">' . $genre->name . '</a>';
 endforeach;
 echo join(', ', $items);
?>
可可 2024-12-21 06:46:26
$temp = array();
foreach($movie->Genres as $genre) {
   $temp[] = <<<EOL
<a href="some_dinamic_link">{$genre->name}</a>
EOL;
}

echo implode(',', $temp);

另一种选择是使用字符串连接,然后使用子字符串来删除结尾的逗号:

$temp = '';
foreach(...) {
   $temp .= ...
}
echo rtrim($temp, ',');
$temp = array();
foreach($movie->Genres as $genre) {
   $temp[] = <<<EOL
<a href="some_dinamic_link">{$genre->name}</a>
EOL;
}

echo implode(',', $temp);

The other option is to use string concatenation, then a substring to delete the trailing comma:

$temp = '';
foreach(...) {
   $temp .= ...
}
echo rtrim($temp, ',');
鹤仙姿 2024-12-21 06:46:26
$a = array();

foreach ( $movie->Genres as $v ){
        $a[] = '<a href="some_link">' . $v->name . '</a>';
}

$s = implode(',', $a);

var_dump($s);
$a = array();

foreach ( $movie->Genres as $v ){
        $a[] = '<a href="some_link">' . $v->name . '</a>';
}

$s = implode(',', $a);

var_dump($s);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文