I recently had to use an object as the source for a grid. The requirement was to have the headers be clickable to sort the columns in ASC and DESC. Typically this is simply a matter of ordering the rows with the SQL query and using the J! framework JHTML::('grid.sort'...) to do the heavy lifting with Javascript.
However, this time, the data was not stored in orderable table columns but in a JSON data store and embeded in a single column. The model would decode the data before passing it to the view to display it. The model had to be to sort the object by different passed criteria before passing it to the view.
I found a great start on php.net usort page from user Lea Hayes. I only had to modify the function with a strnatcmp instead of the listed strcmp to be able to sort on numbers and strings.
function sort_on_field(&$objects, $on, $order = 'asc') {
$comparer = ( $order === 'desc')
? "return -strnatcmp(\$a->{$on},\$b->{$on});"
: "return strnatcmp(\$a->{$on},\$b->{$on});";
usort($objects, create_function('$a,$b', $comparer));
}
...
$order = $this->app->getUserSateFromRequest(...);
$orderDirection = $this->app->getUserStateFromRequest(...)
...
$this->sort_on_fields($this->_data, $order, $orderDirection);
A slight hickup was getting the pagination to work correctly. The fix was to check the old header values with a getUserState() call against the newly specified value with the getUserStateFromRequest() method and then resetting the $limitStart variable if it changed.
