Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

Alphabetise after explode

Posted on 2013-02-04
14
134 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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Currency in SQL? 2 31
Moving from Mcrypt to OpenSSL 18 45
Wordpress Only run code if on a certain page 11 23
Ajax and PHP 4 31
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
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 count occurrences of each item in an array.

828 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