slanton Posted March 15, 2008 Share Posted March 15, 2008 Say I had a table like Fred dog Paul cat Mark cat Fred fish Paul dog and used a query like //$query = "SELECT name, pet FROM clients"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ extract($row); echo $name; echo $pet; } I would get each row as Fred dog, Paul cat, Mark cat Fred fish Paul dog What I am trying to get is an array for each name something like Fred dog fish, Paul cat dog, Mark cat. I can't figure it out! Anyone? Quote Link to comment Share on other sites More sharing options...
p2grace Posted March 15, 2008 Share Posted March 15, 2008 Try this for your query: <?php $query = "SELECT name, pet FROM clients GROUP BY `name`"; ?> Quote Link to comment Share on other sites More sharing options...
slanton Posted March 15, 2008 Author Share Posted March 15, 2008 Using GROUP BY will only return me 3 rows without all the columns eg Paul cat Mark cat Quote Link to comment Share on other sites More sharing options...
sasa Posted March 15, 2008 Share Posted March 15, 2008 try //$query = "SELECT name, pet FROM clients"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_array($result)){ extract($row); //echo $name; //echo $pet; $org_arr[$name][] = $pet; } foreach ($org_arr as $name => $pets){ echo $name, ' - ', implode(', ', $pets), "<br />\n"; } Quote Link to comment Share on other sites More sharing options...
slanton Posted March 15, 2008 Author Share Posted March 15, 2008 Yes thanks that did it. Quote Link to comment Share on other sites More sharing options...
Barand Posted March 15, 2008 Share Posted March 15, 2008 or SELECT name, GROUP_CONCAT(pet SEPARATOR ', ') as pets FROM clients GROUP BY name Quote Link to comment Share on other sites More sharing options...
slanton Posted March 16, 2008 Author Share Posted March 16, 2008 Hi Barand Thanks for that! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.