If you want to sort a class member with the functions uasort, uksort, usort (the u stands for user-defined comparison function) you have to take care of some things.
bool uksort ( array &$array , callable $key_compare_func )
The function takes as first parameter the array you want to sort as reference. Thereby no copy is made to the function stack and any changes are directly made on the origin data. The second parameter is of the type callable – this means you pass a string and php will find the appropriate target (this can be a user function, an object method or static class method).
In my example I will do an object method call. This means I pass an object and the method name to the sort algorithm – this way it can call the sort method of the appropriate object. So it will look like this:
bool uksort ( array &$array , array ( $myObject, 'sortAlgorithm' ) )
Putting it all together:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?php class DataStore { private $data; function __construct() { $this->extract(); $this->sort(); dbg( $this->data ); } private function extract() { $this->data['2025-04-06'] = array( 'title' => 'apple'); $this->data['2010-04-06'] = array( 'title' => 'flower'); $this->data['1990-04-06'] = array( 'title' => 'banana'); $this->data['2011-04-06'] = array( 'title' => 'car'); } private function sortByDateDESC( $a, $b ) { return $b - $a; } private function sort() { uksort( $this->data, array( $this, 'sortByDateDESC' ) ); } } function dbg( $var ) { echo '<pre>'; print_r( $var ); echo '<pre>'; } new DataStore(); |
First I create a new Object of the DataStore – the constructor is called and thereby extract() first. In this function I just create an associative for the member data with a date as key and a dummy value.
Next the sort() function is called which calls uksort. u means: I wan’t to use a custom sort algorithm, k means: I want to sort by the keys only.
The first parameter $this->data is the array that should to be sorted. The second parameter a an array array( $this, 'sortByDateDESC' ) that takes the current object – so just $this and the name of my custom sort algorithm 'sortByDateDESC' that takes care of the comparison logic.
The output is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Array ( [2025-04-06] => Array ( [title] => apple ) [2011-04-06] => Array ( [title] => car ) [2010-04-06] => Array ( [title] => flower ) [1990-04-06] => Array ( [title] => banana ) ) |
Which is pretty much what we wanted to.