ven.ganeva Posted February 25, 2008 Share Posted February 25, 2008 Hi I have a MYSQL query that brings up a number of results in the format of id1, category 1 id2, category 2 id3, category 3 I want to display the categories in a list separated by commas and grammatically correct english like this category 1, category 2 and category 3 Anyone have any ideas? ??? Quote Link to comment https://forums.phpfreaks.com/topic/92876-comma-separated-list-from-values-in-a-database/ Share on other sites More sharing options...
Chris92 Posted February 25, 2008 Share Posted February 25, 2008 If I could see your code I could make something out of it Here's an idea: while( $row = mysql_fetch_assoc($query) ) { $commaList .= "and ".$row['catagory']; $i++; } $exploded = exlode("and ", $commaList, $i); $perfectGrammar = implode(", " $exploded); echo $perfectGrammar; I haven't tested it. Quote Link to comment https://forums.phpfreaks.com/topic/92876-comma-separated-list-from-values-in-a-database/#findComment-475755 Share on other sites More sharing options...
aschk Posted February 25, 2008 Share Posted February 25, 2008 Another option: Using strings <?php // Build dataset while( $row = mysql_fetch_assoc($query) ) { $categories[] = $row['catagory']; } $str = implode(", ",$categories); $pos = strrpos($str,','); echo substr_replace($str,' and ',$pos, ($pos-strlen($str))+2); ?> Quote Link to comment https://forums.phpfreaks.com/topic/92876-comma-separated-list-from-values-in-a-database/#findComment-475771 Share on other sites More sharing options...
ven.ganeva Posted February 25, 2008 Author Share Posted February 25, 2008 Doesn't work, doesn't display the categories at all Quote Link to comment https://forums.phpfreaks.com/topic/92876-comma-separated-list-from-values-in-a-database/#findComment-475799 Share on other sites More sharing options...
wildteen88 Posted February 25, 2008 Share Posted February 25, 2008 Simple example: <?php // array of categories $categories = array('one', 'two', 'three', 'four', 'five'); // take the last category out of the array $lastCat = array_pop($categories); // implode the array and concat the last // category from the array to the end of the string with correct grammer $categoriesList = implode(', ', $categories) . ' and ' . $lastCat; echo $categoriesList; // Output: one, two, three, four and five ?> Quote Link to comment https://forums.phpfreaks.com/topic/92876-comma-separated-list-from-values-in-a-database/#findComment-476163 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.