Reverse Sort Arrays With PHP
While making some changes on my Website, I found some issues with natsort() and array_reverse(). Here is how I did fix it. (July 24, 2009)
First, I tried to make a "20 most viewed pages" section on my website using an array and doing a reverse sorting. It was something like this:
<?php $mostviews = array(); $mostviews[0] = "45733 views howtospeaker"; $mostviews[1] = "5354 views howtothermometer"; $mostviews[2] = "2435 views howtousblight"; $mostviews[3] = "13553 views howtophp"; sort($mostviews); ?> The result: 13553 views howtophp 2435 views howtousblight 45733 views howtospeaker 5354 views howtothermometerTo get the correct order, I have to use the function natsort(). It sorts an array using a "natural order" algorithm, so I get:
2435 views howtousblight 5354 views howtothermometer 13553 views howtophp 45733 views howtospeakerNow, I need to reverse the order, so the last ones with more views are send to the top -I mean; the larger number first.
Well, just I figured that PHP doesn't have a "natrsort();", so I have to do it manually or use an additional function: array_reverse();.
Here is the code:
<?php $mostviews = array(); $mostviews[0] = "45733 views howtospeaker"; $mostviews[1] = "5354 views howtothermometer"; $mostviews[2] = "2435 views howtousblight"; $mostviews[3] = "13553 views howtophp"; natsort($mostviews); array_reverse($mostviews); ?> The result: 2435 views howtousblight 5354 views howtothermometer 13553 views howtophp 45733 views howtospeaker
What could be wrong? Perhaps I should use array_flip()?
No matter what I tried, not even array_reverse(natsort($mostviews)); works. I was not able to reverse the order of the array. Looks like the only solution was to create a process to reverse it "manually".
After a while, I figured the problem: The array_reverse() is not able to reverse the array with the same variable, so the code must be:
<?php $mostviews = array(); $mostviews[0] = "45733 views howtospeaker"; $mostviews[1] = "5354 views howtothermometer"; $mostviews[2] = "2435 views howtousblight"; $mostviews[3] = "13553 views howtophp"; natsort($mostviews); $output = array_reverse($mostviews); unset $mostviews; ?> The result: 45733 views howtospeaker 13553 views howtophp 5354 views howtothermometer 2435 views howtousblightNot quite easy as I thought. Some PHP functions are tricky. I also had another issue with natsort():
I got some files from my digital camera that looks like this:
IMG_00763.JPG IMG_04725.JPG IMG_06453.JPG IMG_00056.JPG IMG_34630.JPG After using natsort() I got: IMG_06453.JPG IMG_04725.JPG IMG_00763.JPG IMG_00056.JPG IMG_34630.JPG
Not exactly the right order. Isn't?
Natsort() function is not able to sort properly numbers with zero padding, negative numbers or symbols like '_' (underscore). So, be aware of this issues and don't waste your time [like I did] thinking you did something wrong in your code.
| < How websites gets hacked. | Homepage php Index |
Sending e-mails with PHP> |
