Jump to content

Comma separated list from values in a database


ven.ganeva

Recommended Posts

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?  ???

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.

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);

?>

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

?>

Archived

This topic is now archived and is closed to further replies.

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