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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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

?>

Link to comment
Share on other sites

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

?>

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.