Array ( [0] => Array ( [dateTime] => 2011-10-18 0:0:00 [chanl1] => 20.7 [chanl2] => 45.4 [chanl3] => ) [1] => Array ( [dateTime] => 2011-10-18 0:15:00 [chanl1] => 20.7 [chanl2] => 45.4 [chanl3] => ) [2] => Array ( [dateTime] => 2011-10-18 00:14:00 [chanl1] => 20.7 [chanl2] => 33.8 [chanl3] => ) [3] => Array ( [dateTime] => 2011-10-18 00:29:00 [chanl1] => 20.6 [chanl2] => 33.9 [chanl3] => )
I want to sort the above array based on the [dateTime], the final output should be:
Array ( [0] => Array ( [dateTime] => 2011-10-18 0:0:00 [chanl1] => 20.7 [chanl2] => 45.4 [chanl3] => ) [1] => Array ( [dateTime] => 2011-10-18 00:14:00 [chanl1] => 20.7 [chanl2] => 33.8 [chanl3] => ) [2] => Array ( [dateTime] => 2011-10-18 0:15:00 [chanl1] => 20.7 [chanl2] => 45.4 [chanl3] => ) [3] => Array ( [dateTime] => 2011-10-18 00:29:00 [chanl1] => 20.6 [chanl2] => 33.9 [chanl3] => )
Is there anyone know how to do it? Thanks!
Sorting a multidimensional array by element containing date. Use the usort() function to sort the array. The usort() function is PHP builtin function that sorts a given array using user-defined comparison function.
The array_multisort() function returns a sorted array. You can assign one or more arrays. The function sorts the first array, and the other arrays follow, then, if two or more values are the same, it sorts the next array, and so on.
To PHP sort array by key, you should use ksort() (for ascending order) or krsort() (for descending order). To PHP sort array by value, you will need functions asort() and arsort() (for ascending and descending orders).
The ksort() function sorts an associative array in ascending order, according to the key. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Tip: Use the asort() function to sort an associative array in ascending order, according to the value.
Use usort()
function with custom comparator:
$arr = array(...); usort($arr, function($a, $b) { $ad = new DateTime($a['dateTime']); $bd = new DateTime($b['dateTime']); if ($ad == $bd) { return 0; } return $ad < $bd ? -1 : 1; });
DateTime class has overloaded comparison operators (<
, >
, ==
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With