, 'opacity': false, 'speedIn': , 'speedOut': , 'changeSpeed': , 'overlayShow': false, 'overlayOpacity': "", 'overlayColor': "", 'titleShow': false, 'titlePosition': '', 'enableEscapeButton': false, 'showCloseButton': false, 'showNavArrows': false, 'hideOnOverlayClick': false, 'hideOnContentClick': false, 'width': , 'height': , 'transitionIn': "", 'transitionOut': "", 'centerOnScroll': false }); })
Home PHP PHP Snippet of the day – Sort Object by field name
formats

PHP Snippet of the day – Sort Object by field name

Published on December 1, 2012 by in PHP

If you find you need to sort an returned object this snippet will save your life.

/** * Sort array of objects by field.
 *
 * @param array $objects Array of objects to sort.
 * @param string $on Name of field.
 * @param string $order (ASC|DESC)
 */
function sort_on_field(&$objects, $on, $order = 'ASC') {
    $comparer = ($order === 'DESC')
        ? "return -strcmp(\$a->{$on},\$b->{$on});"
        : "return strcmp(\$a->{$on},\$b->{$on});";
    usort($objects, create_function('$a,$b', $comparer));
}

//Example Usage:

sort_on_field($view->result,'node_title','ASC');

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
No Comments  comments 
© Brainstorms of a Webdev
credit