Jan
Jan

Reputation: 6828

How to custom sort php objects (elegantly)?

I have a list of ids [1,500,7] and a list of entities with corresponding id properties, but in a different order (1 -> 7, 500). In php, how can I sort them according to the list of ids?

Php version is 5.3.2

Upvotes: 0

Views: 139

Answers (3)

Matthew Scharley
Matthew Scharley

Reputation: 132254

Given some data structures like the following (from your description):

$ids = array(5, 15, 10);
$values = array(
  (object) array('id' => 10, 'data' => 'foo'),
  (object) array('id' => 5, 'data' => 'foo'),
  (object) array('id' => 15, 'data' => 'foo'),
);

You could use something like the following:

// Precalculate sort positions to avoid two calls to array_search for each sort
// operation as that gets costly very quickly.
$id_positions = array_flip($ids);
// Do the actual sorting here.
usort($values, function($a, $b) use ($id_positions) {
  return ($id_positions[$a->id] < $id_positions[$b->id] ? -1 : 1);
});

The above code makes a few assumptions, but should get you on your way.

Upvotes: 4

Dancrumb
Dancrumb

Reputation: 27539

Assuming that the list of IDs and the list of entities are the same length and that every ID has a corresponding entity and that every entity's ID is in the ID list.

$sorted_entities = array();
$sort_order = array_combine($list_of_ids, range(0, count($list_of_ids) - 1));
foreach ($list_of_entities as $entity) {
    $sorted_entities[$sort_order[$entity->id]] = $entity;
}

This has the advantage of traversing each array only once. It has the disadvantage that it does not sort the entities in place.

Upvotes: 0

Carlos Campderr&#243;s
Carlos Campderr&#243;s

Reputation: 22972

You can create a compare function (or method inside a class) that should return a positive, negative or 0 value depending if the first value to compare is greater, lesser or equal to the second value. And then call usort() (in this link you'll find more info about the compare function).

Upvotes: 0

Related Questions