我有一个foreach循环,我想获得第二个回显的$item的计数/总数。有没有一种方法可以对变量进行计数并在foreach循环中显示总数?如果不是,我可以做一个单独的sql并存储计数并将其传递到下面指示的位置吗?或者你可以只返回一个sql数组中的变量吗(在这种情况下是$row)?
结果如下:
成本 项目
成本1 3
成本2 1
成本3 4等。
但是,这些项目与成本不存储在同一个表中。它们通过表ID联接进行连接。因此在foreach中,$cost和$item必须是两个独立查询的结果。我想我的问题是,如果我这样做,每一行如何在循环时知道与每个成本匹配的项目?
foreach ($row as $this) {
echo "<td>$this[cost]</td>";
echo "<td> //want to get count of $item variable here! </td>";
根据我的理解,您希望从不同的表中获得两个值。并且它们与Table_id相连接。为此,你不需要解雇两个绅士。一个用于成本,一个用于物料。
在单个查询中使用join
的更好方法。并同时显示。
select c.cost, i.item
from cost_table c
left join item_table i on i.id = c.id
where something = something
何时可以在foreach中使用
foreach ($row as $this) {
echo "<td> $this[cost] </td>";
echo "<td> $this[item] </td>";
}
要了解有关加入的信息,请访问此处http://www.w3schools.com/sql/sql_join_left.asp
希望它对你有用。。
$counter = count($row); //counts the total elements of $row array
另一种方法是在foreach循环外放置一个计数器,如下所示:
$counter = 0;
foreach ($row as $this) {
echo "<td>$this[cost]</td>";
echo "<td> //want to get count of {$counter} variable here! </td>";
$counter++;
}
稍后编辑以理解我的意思:
$sql_response = mysqli_query($link, "SELECT `product_name`, `product_price` FROM `products` WHERE `product_price`>499"); //let's assume that we have 98 products that meet this condition
$no_of_rows = 0;
if ($sql_response) $no_of_rows = mysqli_num_rows($sql_response); //this will count the number of rows that are in $sql_response right now
echo $no_of_rows; //will output 98 if the query was successfully
如果你有一个数组的元素如下:
$my_array = array( 0 => array( 'test1' => '123'),
1 => array( 'test2' => '123'),
2 => array( 'test3' => '123') );
echo count($my_array); //will output 3