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

时间:2012-07-10 16:44:49

标签: 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)”。

如果当前结果是最后一个怎么办?

4 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

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

除了最后一个结果之外,不要在每个结果后附加逗号,而是尝试在除第一个结果之外的每个结果上预先备用逗号。

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

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

答案 2 :(得分:2)

只需构建您的结果数组并implode即可。这会自动处理任何计数:

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

答案 3 :(得分:1)

您不应该使用普通的mysql访问权限,请查看PDO

回答你的问题,尝试这样的事情:

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