Added on: Thursday 30th July 2009
Good database design says that it would be better to store the values in a table that links the value to a record in another table - allowing multiple values for each record - but I was stuck with the current arrangement so had to make do.
The particular field in the database could contain a single value such as item1 or multiple (comma separated) values in any order such as item2,item1 or item1,item3
The first thing that occurred to me was just to retrieve the records in question and then use PHP to loop through each one, splitting them into individual values. The code would then add the value to an array if it wasn't already in there or ignore it if it was. Finally it would need to sort the array.
This only involves a single call to MySQL but there is still a lot of processing for PHP.
I then decided to make use of the GROUP_CONCAT function in MySQL as follows:
SELECT GROUP_CONCAT(items ORDER BY items SEPARATOR ',') AS items
This produces a single row with a field containing a comma separated list of all possible combinations eg. item1,item1,item3,item2,item1 from the example above.
By making use of the array_unique function in PHP there are only three lines of code required to create the unique sorted list.
$ary = explode(",", $items);
$tags = array_unique($ary);
sort($tags);
I am assuming in the above code that $items is the value of the field resulting from the MySQL query. The script then uses explode to create an array of values - array_unique removes any duplicates and the sort function ensures they are in alphabetical order.
Andrew Parrott runs Round Ash Associates, a web design and development company based in Chagford on Dartmoor, Devon.
If you prefer updates via email then please enter your email address below and click Submit.
If you haven't been to Chagford before then take a look a what you are missing.
Sitepoint is an indespensible resource for web designers.
Internet Explorer isn't the only web browser and from a development point of view Firefox is much better.
As many of the articles on this site are slightly techy I thought I ought to link to a glossary of Internet terms.
The layout for this site uses one of Matthew James Taylors 'liquid layouts'.
©Round Ash Associates 2009. Powered by form2list.