Manual sorting of database output I have a small (few elements) list of primary keys, sorted by hand. It come from user input. For example

$ids = [15, 75, 54, 13];


The SQL command is simple.

SELECT id, value, type FROM a_table WHERE id IN (15, 75, 45, 13);


This is SQL, so the order of output may be random. I want to 
restore it in PHP. My first attempt.

# $ids - the input
# $result - output from database
function sort_to_input_1($ids, $result)
{
    $plain = array_map(function($a){return $a['id'];}, $result);
    $flipped = array_flip($plain);
    $sorted = array();
    foreach($ids as $id) {
        if (isset($flipped[$id])) {
            $idx = $flipped[$id];
            $sorted[] = $result[$idx];
        }
    }
    return $sorted;
}


The second, the brute force.

# $ids - the input
# $result - output from database
function sort_to_input_2($ids, $result)
{
    $sorted = array();
    foreach($ids as $id) {
        foreach($result as $row) {
            if ($row['id'] == $id)) {
                $sorted[] = $row;
            }
        }
    }
    return $sorted;
}


The third one.

# $ids - the input
# $result - output from database
function sort_to_input_3($ids, $result)
    $result_h = array();
    foreach($result as $row) {
        $id = $row['id'];
        $result_h[$id] = $row;
    }
    $sorted = array();
    foreach($ids as $id) {
        if (isset($result_h[$id])) {
            $sorted[] = $result_h[$id];
        }
    }
    return $sorted;
}


Witch one is the easiest to read? Or is there a fourth way?
While technically this isn't reviewing your code, IMO this is the better solution: Do sort via MySQL

SELECT id, value, type 
FROM a_table 
WHERE id IN (15, 75, 45, 13);
ORDER BY FIELD(id, 15, 75, 45, 13)


PHP isn't the fastest language and should therefor not be used for sorting/ordering sets of data if other solutions are present. Looping in PHP is slow (but sometimes negligible, like the while(fetch)). MySQL, in this case, is a whole lot faster then PHP.

At the same time, this is more readable (IMO) and better to maintain.