Solved

Alphabetise after explode

Posted on 2013-02-04
14
133 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
ID: 38851360
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
ID: 38851385
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
ID: 38851407
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
Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

 
LVL 42

Expert Comment

by:sedgwick
ID: 38851413
the $tag is unique ?
0
 

Author Comment

by:djfenom
ID: 38851427
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
ID: 38851465
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
ID: 38851539
No, it should just show them once.
0
 
LVL 109

Expert Comment

by:Ray Paseur
ID: 38866488
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
ID: 38888456
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 109

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 38888576
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
ID: 38888964
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 109

Expert Comment

by:Ray Paseur
ID: 38889812
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 109

Expert Comment

by:Ray Paseur
ID: 38941724
...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
ID: 38941733
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

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
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…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

809 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