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


How can I tell if the current result is the last result in PHP

我有一个用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(乐高城市,乐高星球战争)"。

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

您可以通过从另一个方向攻击它来解决这个问题。

不要在除最后一个结果外的每个结果后都附加逗号,而是尝试在除第一个结果外每个结果上预先挂起逗号。

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

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

如果逗号是第一个结果,请不要添加逗号,并在接下来的所有结果中添加逗号。

只需构建结果数组并将其内爆即可。这会自动处理任何计数:

$comma_separated = implode(",", $array);

你不应该使用普通的mysql访问,看看PDO。

回答你的问题,试试这样的方法:

$items = array();
while ($row = mysql_fetch_assoc($result)) {
  $items[] = $row['foo'];
}
echo implode(', ', $items);