PHP循环,在除最后一个循环外的每个循环后添加一个逗号


PHP Loop, Add a comma after every loop except the last

我有一个查询,它循环遍历一些产品名称并将它们放在页面上。作为循环的一部分,它在末尾添加了一个逗号,所以看起来像这样:

产品:衬衫,裤子,领带,夹克,

注意,我在最后一个产品后面有一个逗号。此外,它们都是链接,所以我不能使用一些strreplace fx或类似的:

这是我的代码:

<?php
 $product_query = mysql_query("select * from products_table);
 $row_product_query = mysql_fetch_assoc($product_query);
 $totalRows_product_query = mysql_num_rows($product_query);
 ?>
 <strong>Products:  </strong>
 <?php if ($totalRows_product_query > 0) {  ?>
 <?php do { ?>
 <span><a href="link"><?php echo $row_product_query['products_name']; ?></a></span>
<strong>,&nbsp;</strong>
 <?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
 <?php } ?><br />

我需要做些什么才能使最后一个逗号不出现?

一如既往地提前感谢。

使用php内爆函数

<?php
    $str = "";
    $product_query = mysql_query("select * from products_table");
    $row_product_query = mysql_fetch_assoc($product_query);
    $totalRows_product_query = mysql_num_rows($product_query);
    $cnt = 0;
?>
<strong>Products:  </strong>
<?php if ($totalRows_product_query > 0) {  ?>
<?php do { 
    $arr[$cnt] = '<span><a href="link">'.$row_product_query['products_name'].'</a></span>';
    $cnt++;
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php } 
    echo implode("<strong>,</strong>",$arr);
?><br />

修复它们是如何存储/输入数据库的?否则<?php echo str_replace(",", "", $row_product_query['products_name']); ?>应该工作

正如@tucker所说,您可以使用内爆函数。Implode函数。你可以把它和这样的数组一起使用

$a_string = implode(",",$the_result_array);

这会给你带来你想要的结果。