Sort PHP arrays by timestamp

I have a problem with arranging the array the way I want.

This is an example of the output of my array: http://pastebin.com/GJNBmqL7

Data comes from different databases at once, so I am limited by how I put the data into an array.

In [2] there is always a linux timestamp. Now I want the whole array to be ordered by this timestamp with the smallest value.

How can i do this?

+8
sorting arrays php
source share
8 answers

here is an array_multisort example:

foreach ($array as $key => $node) { $timestamps[$key] = $node[2]; } array_multisort($timestamps, SORT_ASC, $array); 
+6
source share

use usort, which takes a user-defined function to sort arrays:

usort

your function might look something like this:

 function cmp($a, $b) { if ($a[2] == $b[2]) { return 0; } return ($a[2] < $b[2]) ? -1 : 1; } 
+11
source share

You can do this simply with custom sorting. Therefore, if your date stamp is always listed in index 2:

 function sortArray($a1, $a2){ if ($a1[2] == $a2[2]) return 0; return ($a1[2] > $a2[2]) ? -1 : 1; } usort($array, "sortArray"); 
+6
source share

usort is the easiest to use, but you can also check array_multisort .

+5
source share

Use usort and create your own function, http://php.net/manual/en/function.usort.php

0
source share
 function cmp($a, $b) { if ($a[2] == $b[2]) { return 0; } return ($a[2] < $b[2]) ? -1 : 1; } $data = array( /* your data */ ); usort($data, "cmp"); 
0
source share

It might be easier to insert data into one temporary table, then SELECT, with a timestamp ORDER BY

0
source share

This can be achieved with the following code.

 usort($variable, function ($a, $b) { if ($a['timestamp'] == $b['timestamp']) { return 0; } return ($a['timestamp'] < $b['timestamp']) ? 1 : -1; 

});

This will sort the array of variable $, assuming the timestamp is in Variable $ [0] ['Timestamp']; Variable $ [0] ['Timestamp']; etc.

0
source share

All Articles