我曾经读过一个关于“如何在 php 中将结果分组为子组”的问题(在本论坛中)。我遇到了一个与问题几乎相同的问题。
我有一个像这样的 MySQL 表:
+----------+----------+----------+--------------+-------+-------+--------+
| type | ID | customer | address | bill |service| total |
+----------+----------+----------+--------------+-------+-------+--------+
|water |A1 |jhon |Samrat street |100 |50 |150 |
|electric |A1 |jhon |Samrat street |30 |15 |45 |
|electric |A2 |ana |zero street |20 |10 |30 |
|water |A3 |billy |west street |40 |60 |100 |
+----------+----------+----------+--------------+-------+-------+--------+
我想在通知信中显示表格记录,像这样:
约翰(A1)
萨姆拉特街
+---------+-------+----------+---------+
|type |bill |service |total |
+---------+-------+----------+---------+
|water |100 |50 |150 |
|electric |30 |15 |45 |
+---------+-------+----------+---------+
| grand total|600 |
+----------------------------+---------+
分析(A2)
零街
+---------+-------+----------+---------+
|type |bill |service |total |
+---------+-------+----------+---------+
|electric |20 |10 |30 |
+---------+-------+----------+---------+
| grand total|30 |
+----------------------------+---------+
比利 (A3)
西街
+---------+-------+----------+---------+
|type |bill |service |total |
+---------+-------+----------+---------+
|water |40 |60 |100 |
+---------+-------+----------+---------+
| grand total|100 |
+----------------------------+---------+
实际上,我是使用 FPDF 和 codeigniter 制作外观的。但我假设它是在 PHP 页面中制作的,因为我只想知道如何使用 foreach 方法(php pure 或 codeigniter)进行循环过程。
我希望有人能帮助我。 谢谢你的好意..^^'
最佳答案
试试这个
$query = mysql_query('SELECT * FROM table GROUP BY ID');
foreach (mysql_fetch_object($query) as $row){
$data .= '<div>';
$data .= '<p>' . $row->customer . '(' . $row->ID . ')' . '</p>';
$data .= '<p>' . $row->address . '</p>';
$data .= '<table>';
$query1 = mysql_query('SELECT * FROM table WHERE ID = ' . $row->ID . ' AND customer = "' . $row->customer . '" AND address = "' . $row->address . '"');
$data .= '
<tr>
<td>type</td>
<td>bill</td>
<td>service</td>
<td>total</td>
</tr>
';
$total = 0; //variable initialized for grand total
foreach(mysql_fetch_object($sql1) as $row1){
$data .= '
<tr>
<td>' . $row->type . '</td>
<td>' . $row->bill . '</td>
<td>' . $row->service . '</td>
<td>' . $row->total . '</td>
</tr>
';
$total += $row->total; //adding the total amount for the grand total
}
$data .= '
<tr>
<td colspan="2" align="right">Grand Total</td>
<td colspan="2" align="right">' . $total . '</td>
</tr>
'; //This displays the grand total
$data .= '</table>';
$data .= '</div>';
}
此外,您还可以浏览User Guide of CodeIgniter寻求进一步帮助
关于php - 在子组中分组(使用 php 循环),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5162344/