我想在每篇文章中计算评论..但是评论计数器放在foreach循环之间。所以我无法正确计算评论...所以我想循环但我不需要在柜台循环
articles_controller.php
$count = $this->Article->Comment->find(
'count', array('conditions' => array('Comment.status' => 1))
);
物品/ index.ctp
<?php
// initialise a counter for striping the table
$count = 0;
// loop through and display format
foreach($articles as $article):
// stripes the table by adding a class to every other row
$class = ( ($count % 2) ? " class='altrow'": '' );
// increment count
$count++;
?>
<?php
echo $html->link(
$article['Article']['title'],
array( 'action' => 'view', $article['Article']['id'])
);
?>
<!-- date and comment counter -->
<p class="entry-meta">
<span class="date"><?php echo $article['Article']['created']; ?></span> <span class="meta-sep">|</span>
<span class="comments-link">
<!-- here i will put the comment counter -->
<a href="declining-health.html#respond"> <?php echo $count ['Comment'];>Comments</a>
</span>
</p>
<?php endforeach; ?>
答案 0 :(得分:2)
您可以使用sizeof()
计算数组中的项目数。
答案 1 :(得分:2)
使用Post-&gt; Comment关系中的counterCache属性,并确保在帖子模型中有一个comment_count字段。
IE:
<?php
class Post extends AppModel {
public $name = 'Post';
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'post_id'
)
);
}
?>
<?php
class Comment extends AppModel {
public $name = 'Comment';
public $belongsTo = array(
'Post' => array(
'className' => 'Comment',
'counterCache' => true
)
);
}
?>
// in the database table for table posts make sure to do the following
add a column: comment_count int(11) default 0
现在,当您添加新帖子时,您将拥有一个初始值为0的comment_count字段。当在帖子中添加或删除新评论时,计数值将自动更新。
这允许您简单地遍历posts数组并回显comment_count字段的值或使用该值来检查注释然后嵌入元素等。
答案 2 :(得分:0)
Krisitian给了你答案,但我建议你在前端做你所有的造型。
css伪选择器
//styles every second(even) elements
.your_class:nth-child(2n){background-color:hotpink;}
tr:nth-child(2n){background-color:hotpink;}
...these also work with jquery