Engine23
blogBannerImage
By Engine23

Sorting PHP Objects

// sort an object by key

function sort_object_by_key( $obj, $order='' )
{
    $tmp = array();
    // deconstruct the object into an array
    foreach( $obj as $key => $val )
    {
        $tmp[$key] = '';
    }
   // sort the array
    if($order == 'DESC')
    {
        krsort( $tmp );
    }
    else
    {
        ksort( $tmp );
    }
 // rebuild the object
    $tmpObj = new stdClass();
    foreach( $tmp as $key => $val )
    {
        $tmpObj->$key = $obj->$key;
    }
    return $tmpObj;
}

Sort an object by value

function sort_object_by_value( $obj, $item, $order='' )
{
   $tmp = array();
    // deconstruct the object into an array
    foreach( $obj as $key => $val )
    {
        $tmp[$key] = $val->$item;
    }
    // sort the array
    if( $order == 'DESC' )
{
     asort( $tmp );
    }
    else
    {
        arsort( $tmp );
    }
    // rebuild the object
    $tmpObj = new stdClass();
    foreach( $tmp as $key => $val )
    {
       $tmpObj->$key = $obj[$key];
    }
    return $tmpObj;
 }