Php 如何在foreach循环中查找计数?

Php 如何在foreach循环中查找计数?,php,cakephp,cakephp-1.3,Php,Cakephp,Cakephp 1.3,我想计算每篇文章的评论。但是评论计数器位于foreach循环之间。所以我不能正确计算评论。所以我想要循环,但我不需要计数器中的循环 articles\u controller.php $count = $this->Article->Comment->find( 'count', array('conditions' => array('Comment.status' => 1)) ); 文章/索引.ctp <?php // initialise

我想计算每篇文章的评论。但是评论计数器位于foreach循环之间。所以我不能正确计算评论。所以我想要循环,但我不需要计数器中的循环

articles\u controller.php

$count = $this->Article->Comment->find(
    'count', array('conditions' =>  array('Comment.status' => 1))
);
文章/索引.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; ?>

|


你可以用
sizeof()来计算数组中的项目数
你可以用
sizeof()来计算数组中的项目数
Kristian给了你答案,但我建议你在前端做所有的造型

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

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

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

在Post->Comment关系中使用counterCache属性,并确保在Post模型中有Comment\u count字段

即:


//在表POST的数据库表中,确保执行以下操作
添加列:注释计数int(11)默认值0
现在,当您添加一篇新文章时,您将有一个初始值为0的comment_count字段。当从帖子中添加或删除新评论时,计数值将自动更新


这允许您简单地在Post数组上循环并回显comment_count字段的值,或者使用该值检查注释,然后嵌入元素等。

在Post->comment关系中使用counterCache属性,并确保在Post模型中有comment_count字段

即:


//在表POST的数据库表中,确保执行以下操作
添加列:注释计数int(11)默认值0
现在,当您添加一篇新文章时,您将有一个初始值为0的comment_count字段。当从帖子中添加或删除新评论时,计数值将自动更新


这使您可以简单地在posts数组上循环,并回显comment\u count字段的值,或者使用该值检查评论,然后嵌入元素等。

您的意思是我这样做,我真的不明白。。。我指的不是函数而是mysql代码,比如SELECT count,那么问题出在哪里?您可以从tbl中执行
选择COUNT(*)以获取表中的行数
tbl
。。我不需要循环这个结果你可以做
sizeof($arr)
而不用先循环
$arr
。你的意思是我可以这样做,我想你不明白我的意思。。。我指的不是函数而是mysql代码,比如SELECT count,那么问题出在哪里?您可以从tbl
中执行
选择COUNT(*)以获取表中的行数
tbl
。。我不需要循环此结果,您可以执行
sizeof($arr)
,而无需先循环通过
$arr