简体   繁体   English

如何在PHP中获取对象数组的记录数

[英]How to get record count of an array of objects in PHP

I'm trying to display the total number of records returned from my mongo 3.4 database. 我正在尝试显示从mongo 3.4数据库返回的记录总数。 For this particular query, the results should be 380 but it's showing 14489. I'm sure it's something simple that I'm missing / forgetting about PHP 对于此特定查询,结果应为380,但显示为14489。我确定这很简单,我想念/忘记了PHP

Here's the code: (including some debug statements about the type of variable I'm dealing with) 这是代码:(包括一些有关我正在处理的变量类型的调试语句)

       $numrecords = count($records);                                
       echo"<BR><font color=red>".gettype($records)."</font>";
       echo"<BR><font color=red>".sizeof($records)."</font>";
       if (  $numrecords > 0 ) {
              echo "<tr><td colspan='5'><h3>Record Count: ".$numrecords ."</h3></td></tr>";
              echo "<tr><th>PH Number</th><th>Department</th></tr>";
              foreach ( $records as $rec ) {
                     if (!empty($rec->department)) {                                                                                          
                         echo "<tr>";
                         echo "<td>". $rec->phnum . "</td>";
                         echo "<td>". $rec->department . "</td>";
                         echo "</tr>";
                     }   
              } //end for 
       } else {
              echo "<tr><td colspan='5'>No matching data</td></tr>";                                  
       } 

It says the object type is 'array'. 它说对象类型是“数组”。 I've been playing with count() vs. sizeof() 我一直在玩count()与sizeof()

Any tips would be appreciated. 任何提示将不胜感激。

So it shows the correct number of rows in the table, but the count shows more than what's in the displayed table? 因此,它可以在表中显示正确的行数,但是计数显示的内容多于显示的表中的内容?

Try to use msqli_num_rows after your query 查询后尝试使用msqli_num_rows

Here's an example below, you'll have to change it to your needs since you didn't provide your query code 下面是一个示例,由于您没有提供查询代码,因此必须根据需要进行更改

$sql = "SELECT * FROM table_name WHERE datarow='$datarow'";
$result = mysqli_query($conn, $sql);
//this is where you count the number of rows returned from this query.
$count = mysqli_num_rows($result);

If this doesn't work, there's a problem with your query not meeting the specifications that you desire. 如果这不起作用,则可能是查询不符合所需的规格问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM