views:

70

answers:

1

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 5

I 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 } mysql_close(); ?>

</body>
</html>

Please help!

+1  A: 
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.

Chacha102
Thanks, that worked perfectly!
Michael
If it worked perfectly, you might want to click the green checkmark next to my answer to mark it as correct.
Chacha102
How would you go about adding a second grouping level? Let's say Female Users and Male Users? (Females -> Username -> Items / Males -> Usernames -> Items)
Michael