Link to home
Start Free TrialLog in
Avatar of bergstrom_davin
bergstrom_davin

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of Rurne
Rurne
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Avatar of blue_hunter
blue_hunter
Flag of Malaysia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of bergstrom_davin
bergstrom_davin

ASKER

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;
}