Grouped/Stratified Reports using PHP and MySQL
I am trying to generate a grouped/stratified report using PHP and MySQL.
tbl_items has the following fields: (1) UserName and (2) ItemName
A single user can have multiple items listed.
I want to generate an output where the data is stratified by each user. For example:
*UserName #1
-ItemName 1 -ItemName 2 *UserName #2 -ItemName 3 *UserName #3 -ItemName 4 -ItemName 5I keep playing with the code, trying to put a loop inside a loop...but can't figure out how to do it! This is what I have so far:
<?
$sql="SELECT * FROM $tbl_items";
$result=mysql_query($sql);
?>
<html>
<body>
<? php while($rows=mysql_fetch_array($result)){ ?>
Item: <? echo $rows['ItemName']; ?> (<? echo $rows['UserName']; ?>)
<?php开发者_C百科 } mysql_close(); ?>
</body>
</html>
Please help!
while($row=mysql_fetch_array($result))
{
$itemsByUser[$row['UserName']][] = $row;
}
foreach($itemsByUser as $user => $items)
{
echo $user . "<br>";
foreach($items as $array)
{
echo "-" . $array['ItemName'];
}
}
This first creates an array that is order by Username. This means each user has an element in the array that contains an array of the items that have been assigned to the user.
Then, we go over each user and print out all of the items.
精彩评论