Jump to content

Showing values horizontally by using array or multidimension array


draconlock

Recommended Posts

Hi guys, I'm very new at this php and ive been doing alot of research and I can't seem to get what I want and I figured you guys always have the answers so here it goes.

 

Here is what the table in the db looks like:

table1

iduseridproductqty

11paper20

21pencil40

31pen50

42paper20

52pen60

 

Here is my select statement:

$query ="SELECT * FROM table1";

$result = mysql_query($query);

 

Here is my current code and it currently prints out every line correctly but...:

while ($data = mysql_fetch_object($result)) 

{

$index = $data->id;

$userid = $data->userid;

$product = $data->product;

$quantity= $data->qty;

 

$printdata = [][]=array("$index","$userid ","$product","$quantity");

}

 

I want it to display like below but by using an array?

[/td]paperpencilpen

1204050

220[td]60

 

Could anyone please help me I would greatly appreciate it.  Thank you.

That is a poorly designed database structure. You should have a separate table for the product names and then just reference the product ID in this table. WOuld make this much, much easier. But, using the structure you have, this should work (not tested so there may be some minor errors)

 

<?php

$query ="SELECT userid, product, SUM(qty) as qty
         FROM table1
         GROUP BY userid, product
         ORDER BY userid, product";
$result = mysql_query($query);

$products = array();
$userData = array();

while ($data = mysql_fetch_object($result))   
{
    //Add product to array if not already exist
    if (!in_array($data->product, $products))
    {
        $products[] = $data->product;
    }
    //Add user data to array
    if (!isset($userData[$data->userid]))
    {
        $userData[$data->userid] = array();
    }
    $userData[$data->userid][$data->product] = $data->qty;
}
//Create table
echo "<table>\n";
//Create headers
echo "<th></th>\n";
foreach ($products as $product)
{
    echo "<th>$product</th>\n";
}
//Write user data
foreach($userData as $userID => $data)
{
    echo "<tr>\n";
    echo "<td>$userID</td>\n";
foreach ($products as $product)
    {
        echo "<td>$data[$product]</td>\n";
    }
    echo "</tr>\n";
}
echo "</table>\n";
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.