我有一个按访问次数排列的文章表,其中访问次数最多,即排名为1.我尝试在表格中添加Rank列,但不能让它工作。数据库中不存在Rank列,因此这应该是一个以1开头并以表中列出的文章数结束的增量计数器。 这是我的代码,不起作用
<table class="resultsTable" width="100%">
<tr>
<th style="width:10%">Rank</th>
<th style="width:50%">Post Title</th>
<th style="width:20%">Post Type</th>
<th style="width:20%">Hits</th>
</tr>
<?php foreach($popular_articles as $article) {
//create array for most popular
?>
//set counter variable
$counter = 1;
while($row = mysql_fetch_array($result))
<tr>
echo "<td style="width:10%">".$counter."</td>";
<td style="width:50%"><?php echo $article->art_title; ?></td>
<td style="width:20%"><?php echo $article->art_type; ?></td>
<td style="width:20%"><?php if($article->art_hit_count){ echo '<b>'.$article->art_hit_count.'</b>'; }else { echo '<b>0</b>'; } ?> times.</td>
</tr>
$counter++; //increment counter by 1 on every pass
echo <?php } ?>
</table>
答案 0 :(得分:0)
增加计数器必须在PHP中完成。目前,这行是在HTML中:
$counter++; //increment counter by 1 on every pass
我还删除了while
,因为它似乎没有做任何事情,就好像是在那里意外粘贴一样。
循环应如下所示:
<?php
foreach($popular_articles as $article) {
//set counter variable
$counter = 1;
<tr>
<td style="width:10%"><?php echo $counter; ?></td>";
<td style="width:50%"><?php echo $article->art_title; ?></td>
<td style="width:20%"><?php echo $article->art_type; ?></td>
<td style="width:20%"><?php
if($article->art_hit_count){
echo '<b>'.$article->art_hit_count.'</b>';
}else {
echo '<b>0</b>';
} ?> times.</td>
</tr>
<?php
$counter++; //increment counter by 1 on every pass
} ?>
或者,您可以显示计数器并一次更新:
<td style="width:10%"><?php echo $counter++; ?></td>";
...
<?php
// $counter++; // You won't be needing this anymore.
} ?>
答案 1 :(得分:0)
我认为你错过了在循环之前初始化你的计数器(在评论中,我可以看到$ counter = 1,但它已经被执行了。
最后,你尝试增加一个变量,但你不是在PHP脚本中,所以它无法工作。试试我的更正版本,看它是否有效。
<table class="resultsTable" width="100%">
<tr>
<th style="width:10%">Rank</th>
<th style="width:50%">Post Title</th>
<th style="width:20%">Post Type</th>
<th style="width:20%">Hits</th>
</tr>
<?php
$counter = 1;
foreach($popular_articles as $article) {
//create array for most popular
?>
<tr>
<td style="width:10%"> <?php echo $counter; ?></td>;
<td style="width:50%"> <?php echo $article->art_title; ?></td>
<td style="width:20%"> <?php echo $article->art_type; ?></td>
<td style="width:20%">
<?php if($article->art_hit_count){
echo '<b>'.$article->art_hit_count.'</b>';
} else {
echo '<b>0</b>';
} ?> times. </td>
</tr>
<?php
$counter++; //increment counter by 1 on every pass
} //the end of FOR loop ?>
</table>
修改强>
如果您想为art_title建立链接。只需替换此行:
<td style="width:50%"> <?php echo $article->art_title; ?></td>
通过这个:
<td style="width:50%"><a href="your-link.com/page-you-wanna-show.php"> <?php echo $article->art_title; ?></a></td>