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? Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/ 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`"; ?> Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-492724 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 Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-492734 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"; } Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-492762 Share on other sites More sharing options...
slanton Posted March 15, 2008 Author Share Posted March 15, 2008 Yes thanks that did it. Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-492770 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 Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-492779 Share on other sites More sharing options...
slanton Posted March 16, 2008 Author Share Posted March 16, 2008 Hi Barand Thanks for that! Link to comment https://forums.phpfreaks.com/topic/96242-manipulating-mysql_fetch_array/#findComment-493114 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.