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
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
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.
$aPosition and bPosition are identical, which can happen. In this example, it will be as if $aPosition "won".id implies some level of uniqueness in the data.$values are compared. You might want to memoize the results of your array_search calls, if $values gets largearray_search may become important.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).
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.