Sorting an array of objects - OOP PHP

I would like to sort an array of objects by a variable of an object variable.

I have an array of objects (obj_array).
One of the variables of (obj_a) is an object (obj_b).
I want to sort by a variable of (obj_b).

So I want to sort an
$obj_array = array (
      $butter = new obj_a,
      $flour = new obj_a,
      $water = new obj_a
);
by obj_a->obj_b->volume

where obj_a has a variable object called obj_b and obj_b has variable called volume
LVL 1
bergstrom_davinAsked:
Who is Participating?
 
RurneCommented:
To do that, you're going to need to define a side function for basic comparison.  With that defined, you then sort using usort().


function mySort($a, $b){
    $sub_object_a = $a->obj_b;
    $sub_object_b = $b->obj_b;

    if($sub_object_a->volume == $sub_object_b->volume){
       return 0;
    }

    return ($sub_object_a->volume > $sub_object_b->volume) ? 1 : -1;
}

usort($obj_array, "mySort);


More Info:
http://us.php.net/manual/en/function.usort.php
0
 
blue_hunterTechnical ConsultantCommented:
see if you can arrange your array as below

$butter = new obj_a;
$flour = new obj_a;
$water = new obj_a;

$obj_array = array();
$obj_array[$butter->obj_b->volume] = $butter;
$obj_array[$flour->obj_b->volume] = $flour;
$obj_array[$water->obj_b->volume] = $water ;


ksort($obj_array);
$obj_array = array_values($obj_array);

0
 
bergstrom_davinAuthor Commented:
Thank you Rurne, but I was still having trouble with sorting objects of objects by something other than volume.

Thank you blue_hunter, I liked your approach but I would lose $butter or $water if they had the same volume.

Below is a working solution I put together from both your ideas.

function sortby ($sortby = "linkid") {
  // key by sort
  foreach ($this->links as $key => $link) $sorted[$key] = $link->original->{$sortby};

  // sort by key if this sort and last sort are the same then reverse sort
  if ($sortby == $this->sortby) arsort($sorted);      // up
  else asort($sorted);                  // down

  // rekey with id
  foreach ($sorted as $key => $value) $rekeyed[$key] = $this->links[$key];
 
  // save sorted array
  $this->links = $rekeyed;

  // update sort for use in next pass to determine direction
  if ($sortby != "linkid") $this->sortby = $sortby;
}
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.