TDAndT

Total Design and Technology - Websites and Mobile Applications

Sorting an array object for headers

Rate this item
(0 votes)

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.

Royce

Royce

Still here after all these years! 

@joomflix

Website: www.tdandt.com

Image Gallery

More in this category: « Prev

Add comment


Musings, Hopes and Geeks

About Me

I've been a developer for several decades. For the past few years, I've specialized in web development and applications for small and medium businesses. I am also heavily involved in mobile augmented reality (AR) with the Layar platform. My main AR site is at AltWhatNow.

Hire me

We love to receive email. Drop us a line here..
CAPTCHA ImageReload Image