?
Solved

Alphabetise after explode

Posted on 2013-02-04
14
Medium Priority
?
141 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
[X]
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
  • 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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 111

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 111

Accepted Solution

by:
Ray Paseur earned 1500 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 111

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 111

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn how to count occurrences of each item in an array.
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 …
Suggested Courses

770 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