Tuesday 15 February 2011

sorting - How to sort PHP multidimensional array by timestamp -


I am currently walking with Twitter API, but this question is not really related to Twitter API; This is just a normal PHP question.

I am pulling some questions of tweets separately and then amending the requests together. And so, basically, I end up with a final array at the end where tweets are not necessary in the right chronological order:

  $ tweets = array (array ('text '= & Gt;' some tweets. ',' Time '=' sat 22 Jun 00:45:37 +0000 2013 '), array (' text '= & gt; and second.,' Time '=> Friday June 21 15:32:34 +0000 2013 '), array (' text '=> another tweet.', 'Time' => Fri 21 June 17:24: 44 +0000 2013 '), array ( 'Text' = & gt; 'and another tweet.', 'Time' => Fri Jun 21 08:37:37 +0000 2013 '));   

And now I am trying to figure out that the best way to sort the descending order by the timestamp of each array is the best way.

I am reading about usort and uasort , but I just do not quite understand them, as well as in comparison How will this timestamp be used, so any help here would be appreciated. thank you in advanced!

There are two parts to this question.

First of all, you need a way to compare it twice - a direct string comparison of the time in the given format will not give you any useful information you can use to convert the wire into a Unix timestamp. Which is just a few seconds - allows you to easily compare.

  $ ts = strtoom ($ item ['time']);   

The second part is actually sorting the array. You can do this and thus a callback function:

  function do_compare ($ item1, $ item2) {$ ts1 = strtotime ($ item1 ['time']); $ Ts2 = Stratetime ($ item 2 ['time']); Return $ ts2 - $ ts1; } Usort ($ Tweets, 'do_compare'); Tweets in tweets in // $ are now sorted by time   

usort () works by calling your function - either named Or unnamed - every time it needs to compare two elements. If your item is equal to zero, then you need to return to a lower number than zero, if the first thing comes first, if it is zero, or greater than zero then the first thing will be second. In your example, we reduce the timestamp before the second to achieve this value (if the first item is bigger, the result will be negative, by putting it first - descending order). The actual numerical value does not matter - it is less than zero, equal to or greater than zero.

There is another way to do this without the need for a named function - or <. > This will look like this:

  usort ($ tweets, function ($ item1, $ item2) {$ ts1 = strtotime ($ item1 ['time']); $ ts2 = strtotime ($ Item2 ['Time']); $ ts2 - $ ts1;};; // $ items in items are now sorted by time   

This is essentially the same as the first solution, Except that instead of referring back to the name of a function we are defining the function inline which is already defined.

No comments:

Post a Comment