[英]How to count total number of rows in a view which retrieved from database
我想在表格中显示一些列。 另外,想要计算表中显示的总行数。 我尝试了一些方法,如果这是正确的方法或有其他更好的方法可以帮助我。
我的模特
public function getRentedEquipments($project_id=0){
return $this->db->select('e.*, p.project_id')
->from('equipment AS e')
->join('project AS p', 'p.project_id = e.project_id')
->where('p.project_id', $project_id)
->order_by('eq_name','ASC' )
->get()->result_array();
}
我的看法
<tbody>
<?php
$total_eq=0;
$count=1;
foreach ($pr_eq as $row) {
?>
<tr>
<th scope="row"><?php echo $count;?></th>
<th scope="row"><?php echo $row['eq_id'];?> </th>
<th scope="row"><?php echo $row['eq_name'];?> </th>
<?php
$total_eq+=$row['eq_id']-1;
$count=$count+1;
}
?>
<button class="btn btn-info"> Number of Equipments: <?php echo $total_eq;?></button>
</tbody>
恕我直言,没有必要以这种方式计算您的物品 - 试试这个
<tbody>
<?php
foreach ($pr_eq as $row)
{
?>
<tr>
<th scope="row"><?php echo $count;?></th>
<th scope="row"><?php echo $row['eq_id'];?> </th>
<th scope="row"><?php echo $row['eq_name'];?> </th>
</tr>
<?php
}
?>
</tbody>
<button class="btn btn-info"> Number of Equipments: <?= count($pr_eq);?></button>
我们可以更进一步地添加对数组的一些检查(在这种情况下这有点矫枉过正,因为模型中使用的 ->result_array() 将始终返回一个数组)并使用 php 的 if () ; 结束; 使用嵌入式 HTML 可以提高可读性的功能。
<?php
// If we have an array get the count, else its 0
$equipment_count = is_array($pr_eq) ? count($pr_eq) : 0;
// If we have a count > 0 , it must be an array
if ($equipment_count > 0): ?>
<tbody>
<?php foreach ($pr_eq as $row): ?>
<tr>
<th scope="row"><?php echo $count; ?></th>
<th scope="row"><?php echo $row['eq_id']; ?> </th>
<th scope="row"><?php echo $row['eq_name']; ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
<?php endif; ?>
<button class="btn btn-info"> Number of Equipments: <?= $equipment_count; ?></button>
从技术上讲,您可以拥有一个计数为 0 的数组,该数组将无法执行 foreach,无论如何它都会执行。 所以这一切看起来都很安全。
我有你的<tbody>
标签在条件中,所以如果他们需要在外面,你可以修复它以适应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.