2011-12-29 203 views
0

我想在每一篇文章..但的foreach loop..so我不能正确计算评论的评论柜台的地方来算的意见,所以,我想循环,但我不需要循环的计数器如何在foreach循环中查找count?

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; ?> 

回答

2

使用在后>注释关系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场当一个新的注释添加或删除一个帖子计数值将自动地更新。

这可以让你简单地遍历所有的帖子阵列和呼应COMMENT_COUNT字段的值或使用该值检查意见,然后嵌入元素等

+0

abba thannnnnnks ..更多谢谢..更好的解决方案.. – user1080247 2011-12-30 20:37:30

2

你可以指望在sizeof()出数组中元素的个数。

+0

你的意思是ID做到这一点<?PHP的回声的sizeof( $ count ['Comment']);> – user1080247 2011-12-29 15:24:24

+0

我tjink你不了解我...计数我的意思不是功能,但像这样的mysql代码SELECT COUNT – user1080247 2011-12-29 15:26:24

+0

那么问题是什么?你可以做'SELECT COUNT(*)FROM tbl'来获得表'tbl'中的行数。 – kba 2011-12-29 15:26:42

0

克里斯蒂安给了你答案,但我可以建议你在前端做所有你的造型。

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