Jump to content

[SOLVED] Restructure a query???


jtsymbo

Recommended Posts

Bear with me, I'm new at this. I have a query that I want to display in a table format on a web page. I call up the following recordset. Name, Color and Rank are the fields. The results of the query are:

name color rank

jim orange 1

jim blue 2

jim red 3

bob brown 1

bob green 2

bob purple 3

sue gray 1

sue black 2

sue white 3

 

I want to reconfigure the above results to display in a table format as follows:

 

rank jim bob sue

1 orange brown gray

2 blue green black

3 red purple white

 

Jim, Bob, Sue and rank now become the table headings and the colors associated with those people are in rows ordered by rank.

 

I'm not sure how to approach it. Another forum recommended converting the query into an array, but after much head banging and research I'm not sure how to do it. Thanks for any help!

Link to comment
Share on other sites

try this

<?php 
$colors = array();

$sql = "SELECT name,color,rank FROM color";
$res = mysql_query($sql) or die (mysql_error()."<p>$sql</p>");
while (list($n, $c, $r) = mysql_fetch_row($res)) {
    $colors[$n][$r] = $c;              // store in array
}

// inspect array of stored data
echo '<pre>', print_r($colors, true), '</pre>';

// output the results
echo "<table border ='1'>";
echo "<tr><th>Rank</th>";
// heading row
foreach ($colors as $name => $v) {
    echo "<th>$name</th>";
}
echo "</tr>";

for ($r=1; $r<=3; $r++) {
    echo "<tr><th>$r</th>";
    foreach ($colors as $prefs) {
        echo "<td>$prefs[$r]</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.