Jump to content

[SOLVED] grouping Names under Locations?


liquid79

Recommended Posts

Hi Guys,

 

I’m having problems grouping data (names) under Places for an example:

 

In a table I have:

 

Name | Location

 

Bob  | London

John | Wales

Mark | London

Tom | Scotland

Fran | Wales

 

I’m trying to get it to display like:

 

 

--------------------------

 

London

Bob

Mark

 

Scotland

 

Tom

 

Wales

 

John

Fran

 

--------------------------------------

 

I can display it like:

 

London

 

Bob

 

London

 

Mark

 

But I can’t work out how to not have duplicating place names and just to group them under one place name rather than one for each? It be great if anyone can point me into the right direction, Thanks (btw i tryed the Group by but that only displayed half of the data)

 

My code:

 

$ordering = mysql_query("SELECT * FROM test ORDER BY location DESC ");

if (mysql_num_rows($ordering) > 0) {
while ($row = mysql_fetch_object($ordering)) {

echo '<table width="520" border="0" cellspacing="2" cellpadding="2">
  <tr>
    <td><strong>'.$row->location.'</strong></td>
  </tr>
  <tr>
    <td>'.$row->name.'</td>
  </tr>
</table>';
}
}

 

Link to comment
Share on other sites

<?php

$query = mysql_query("SELECT location FROM test ORDER BY location DESC") or die(mysql_error());

while(list($loc) = mysql_fetch_row($query)) {
echo "<strong>{$loc}</strong><br /><br />\n\n";
$query2 = mysql_query("SELECT name FROM table WHERE location = '{$loc}'") or die(mysql_error());
while(list($name) = mysql_fetch_row($query2)) {
  echo "{$name}<br />\n";
}
echo "<br />\n";
}

?>

 

Try that :)

 

EDIT: Darn it, p2grace's looks much prettier!

Link to comment
Share on other sites

something like this

 

$ordering = mysql_query("SELECT * FROM test ORDER BY location DESC ");

if (mysql_num_rows($ordering) > 0) {

$last_location = '';
while ($row = mysql_fetch_object($ordering)) {

echo '<table width="520" border="0" cellspacing="2" cellpadding="2">';
if ($last_location != $row->location) {
echo '<tr>
    <td><strong>'.$row->location.'</strong></td>
  </tr>
';
$last_location = $row->location;
}
echo '  
  <tr>
    <td>'.$row->name.'</td>
  </tr>
</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.