[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 148
  • Last Modified:

Alphabetise after explode

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
djfenom
Asked:
djfenom
  • 6
  • 4
  • 4
1 Solution
 
Meir RivkinFull stack Software EngineerCommented:
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
 
Meir RivkinFull stack Software EngineerCommented:
btw, u don't need array $alltags anymore, cause u have it in the $alltags_echos dictionary as the keys.
0
 
djfenomAuthor Commented:
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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
Meir RivkinFull stack Software EngineerCommented:
the $tag is unique ?
0
 
djfenomAuthor Commented:
Not necessarily, more than one article could use the same tag, that's why I used DISTINCT in my query.
0
 
Meir RivkinFull stack Software EngineerCommented:
but the result of your query are distinct (as you say), which means no multiple $tags should be queried, right?
0
 
djfenomAuthor Commented:
No, it should just show them once.
0
 
Ray PaseurCommented:
Suggest you try ordering the query results set like this:

$query_RStags = "SELECT DISTINCT blogTags FROM news ORDER BY blogTags";
0
 
djfenomAuthor Commented:
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
 
Ray PaseurCommented:
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
 
djfenomAuthor Commented:
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
 
Ray PaseurCommented:
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
 
Ray PaseurCommented:
...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
 
djfenomAuthor Commented:
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: 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.

  • 6
  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now