Solved

Alphabetise after explode

Posted on 2013-02-04
14
126 Views
Last Modified: 2013-03-01
I have a blog page which lists tags relating to particular blog articles.

The tags are displayed on the page and are populated from a database.

Tags are allocated to a particular blog and are then held in one field separated by a comma.

The tags are written to the page using the following code:

$query_RStags = "SELECT DISTINCT blogTags FROM news";
$RStags = mysql_query($query_RStags, $conn) or die(mysql_error());
$row_RStags = mysql_fetch_assoc($RStags);
$totalRows_RStags = mysql_num_rows($RStags);

$alltags = array();
		do { 
			foreach(explode(',', $row_RStags['blogTags']) as $tag) {
				$taglink = strtolower(str_replace(' ','_',$tag));
				if (!in_array($tag, $alltags)) {
					if ($tag !="") {
						if ($_GET['cat'] == $taglink) { $state = ' class="onstate"'; } else { $state = ''; }
						array_push($alltags, $tag);
						$catcount = mysql_query("SELECT * FROM news WHERE blogTags LIKE '%" . $tag . "%'", $conn);
						$catrows = mysql_num_rows($catcount);
						echo "<li><a href=\"/news/category/{$taglink}\"{$state}>{$tag}</a> ({$catrows})</li>\n";
					}
				}
			}

Open in new window


This works great, but my question is, how do I get the tags to come out in alphabetical order? I've looked at Sort, but can't work out where I would use it?

Thanks,

Chris
0
Comment
Question by:djfenom
  • 6
  • 4
  • 4
14 Comments
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
store the echo output in array, after iteration, sort and echo:


$query_RStags = "SELECT DISTINCT blogTags FROM news";
$RStags = mysql_query($query_RStags, $conn) or die(mysql_error());
$row_RStags = mysql_fetch_assoc($RStags);
$totalRows_RStags = mysql_num_rows($RStags);

$alltags = array();
$alltags_echos = array();
		do { 
			foreach(explode(',', $row_RStags['blogTags']) as $tag) {
				$taglink = strtolower(str_replace(' ','_',$tag));
				if (!in_array($tag, $alltags)) {
					if ($tag !="") {
						if ($_GET['cat'] == $taglink) { $state = ' class="onstate"'; } else { $state = ''; }
						array_push($alltags, $tag);
						$catcount = mysql_query("SELECT * FROM news WHERE blogTags LIKE '%" . $tag . "%'", $conn);
						$catrows = mysql_num_rows($catcount);
						$alltags_echos[$tag] = "<li><a href=\"/news/category/{$taglink}\"{$state}>{$tag}</a> ({$catrows})</li>\n";
					}
				}
			}

ksort($alltags_echos);

foreach ($alltags_echosas $key => $val) {
echo  $val;
}

Open in new window

0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
btw, u don't need array $alltags anymore, cause u have it in the $alltags_echos dictionary as the keys.
0
 

Author Comment

by:djfenom
Comment Utility
Thanks sedgwick, before I had:

c tag (1)
b tag (1)
a tag (1)

After adding your code it now comes out as:

c tag (1)
b tag (1)
c tag (1)
a tag (1)
b tag (1)
c tag (1)

Any ideas?

Chris
0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
the $tag is unique ?
0
 

Author Comment

by:djfenom
Comment Utility
Not necessarily, more than one article could use the same tag, that's why I used DISTINCT in my query.
0
 
LVL 42

Expert Comment

by:sedgwick
Comment Utility
but the result of your query are distinct (as you say), which means no multiple $tags should be queried, right?
0
 

Author Comment

by:djfenom
Comment Utility
No, it should just show them once.
0
Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Suggest you try ordering the query results set like this:

$query_RStags = "SELECT DISTINCT blogTags FROM news ORDER BY blogTags";
0
 

Author Comment

by:djfenom
Comment Utility
Sorry for the delay.

The order by won't work as the field blogTags can have multiple tags in it separated by a comma.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
A data base that has multiple data items in a single column is misdesigned.  Make a Google search for the exact phrase, "Should I Normalize my Database" and read the very interesting ideas on each side of the argument.  A correct design would have a junction table that contained the keys of the blog articles and the keys of the blog tags (a many-to-many relationship).  Then the "relational" nature of the data base would make this amazingly easy.

As it stands, the code is so tightly nested with multiple overloaded function calls that I cannot readily see where the blogtags might be isolated.  If you can modify the code to show us, via var_dump(), when the blogtags variable exists and that it contains a comma-separated string of values, then perhaps we can make a copy of that variable.  With the copy we can certainly use explode() and sort() to create a satisfactory ordering.  It may be necessary to use usort() but we won't know that until we see the variable in isolation.
0
 

Author Comment

by:djfenom
Comment Utility
Thanks Ray, unfortunately it's not an option to change the database design at this stage.

Where would I put var_dump() in my code?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
I have no idea where to put var_dump()!  I cannot understand the code well enough because of the function overloading. You might try deconstructing this statement to get an intermediate array that you could visualize with var_dump()

foreach(explode(',', $row_RStags['blogTags']) as $tag) {
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
...unfortunately it's not an option to change the database design at this stage.
And it's not an option to get correct output from a misdesigned data base!

A professional would make a copy of the data base, modify the structure, revise the code, test the new data base, and once satisfied that things were working correctly, push the build to enable the new functionality.  It could reasonably be expected to take the better part of a day.  And you would probably need to take the site down for a few minutes during the switchover  We all make mistakes, and the design of this data base is a mistake.  It should be corrected

And a professional would not try to learn PHP by copying Dreamweaver code, either.  If you want to get a foothold in how to write PHP, this book will give you a head start.  By the time you get to page 325, you'll never need to look to Dreamweaver again!
http://www.amazon.com/PHP-MySQL-Web-Development-Edition/dp/0672329166/
0
 

Author Comment

by:djfenom
Comment Utility
Don't have a cow man!

So I'm clearly not a 'professional' like you, you've ascertained that, I've given you the points, now move on and don't shoot me down.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now