php - 我如何判断当前结果是否是 PHP 中的最后一个结果

标签 php mysql while-loop

我有一个用 PHP 和 MySQL 编写的新在线商店。

<div class="content-area">
<div class="page-heading">
<h1>Store</h1>
</div>
<p style="padding-top: 5px;"><strong>You are here:</strong> <a href="<?php echo $cls->root(); ?>/">Home</a> &raquo; Store</p>
<table border="0" cellpadding="0" cellspacing="0" width="500">
<?php
$categories=mysql_query("SELECT * FROM categories WHERE parent='0' ORDER by owner ASC, title ASC");
while($categoriesRow=mysql_fetch_array($categories)) {
$categoriesSub=mysql_query("SELECT * FROM categories WHERE parent='$categoriesRow[id]'");
?>
<tr>
<td valign="top">
<div class="product_list">
<div class="image_product">
<img alt="<?php echo $categoriesRow['title']; ?>" src="<?php echo $cls->truska(true); ?>/theme_section_image.gif" border="0" style="vertical-align: middle;" />
</div>
<div>
<h3 class="product"><a href="<?php echo $cls->root(); ?>/category/<?php echo $categoriesRow['permalink']; ?>/" target="_self"><?php echo $categoriesRow['title']; ?></a> <?php if(mysql_num_rows($categoriesSub) > 0) { ?>(<?php while($categoriesSubRow=mysql_fetch_array($categoriesSub)) {  }?>)<?php } ?></h3>
</div>
</div>
</td>
</tr>
<tr>
<td class="dotted_line_blue" colspan="1">
<img src="<?php echo $cls->truska(true); ?>/theme_shim.gif" height="1" width="1" alt=" " />
</td>
</tr>
<?php
}
?>
</table>
</div>

我的第二个 While 循环在哪里,我需要计算出最后的结果是什么,所以我可以从我的 while 循环中省略一个逗号。

它将显示为“Lego (Lego City, Lego Starwars,)”,但我希望它显示为“Lego (Lego City, Lego Starwars)”。

如果当前结果是最后一个,如何获取?

最佳答案

您可以从另一个方向解决这个问题。

与其在除最后一个结果之外的每个结果后附加逗号,不如尝试在除第一个结果之外的每个结果前附加一个逗号。

在循环外设置一个名为 $first 的变量,并将其设置为 1。在循环内:

if ($first == 0) {
   echo ",";
} else {
    $first = 0;
}

关于php - 我如何判断当前结果是否是 PHP 中的最后一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11417997/

相关文章:

c - 扫描字符串直到 ":"

php - 删除旧的迁移差异

php - 如何阻止 CakePHP 在输出中放置注释标签

mysql - 计数和分组依据

php - 我可以从一个基于多个其他表的表中获取数据吗?

c++ - while 循环跳过行

javascript - Ajax 成功与错误

php - 被拒绝 Apache2

php - 如何在数据库的不同行中保存多个复选框值

c# - 永远迷失在 if、while 和 foreach 语句中——无法获得适当的运行条件