Possible Duplicate:
mysql custom sort
I have an array of IDs:
$ids = array(5, 1, 4, 2, 3);
and I make a query:
SELECT * FROM Persons
WHERE id IN $ids
and I receive this object:
1, 2, 3, 4, 5
Is it possible to sort this same as in array? I would like receive
5, 1, 4, 2, 3.
I also use PROPEL. Maybe with Propel ORM in Symfony, is this possible?
in mysql you can use the field function for custom sort order. For example:
$ids = array(5, 1, 4, 2, 3);
$ids = implode(',', $ids);
$sql = "SELECT * FROM Persons
WHERE id IN ($ids)
ORDER BY FIELD(id, $ids)";
You can sort it in PHP after you run the query.
Something like this (PHP 5.3+ only):
$ids = array(5, 1, 4, 2, 3);
// Run Query...
// assume $results is the result array
usort($results, function($a, $b) use($ids){
$a = array_search($a['id'], $ids);
$b = array_search($b['id'], $ids);
return $a -$b;
});