phparrayssorting

Sort a 2d array by a column with dynamic control of direction


I have an array, like this:

Array
(
    [0] => Array
        (
            [record_id] => 21
            [quality] => 3
        )

    [1] => Array
        (
            [record_id] => 20
            [quality] => 3
        )

    [2] => Array
        (
            [record_id] => 19
            [quality] => 3
        )

    [3] => Array
        (
            [record_id] => 18
            [quality] => 2
        )

    [4] => Array
        (
            [record_id] => 17
            [quality] => 3
        )

)

I need to be able to order the array by highest to lowest (regarding the quality key) in ascending order or descending (when a mode has been selected), so for example I need it to order an array and return it ordered, e.g.

function order_array($array, $order = 'asc')
{
   if($order == 'asc')
   // order the array from lowest to highest

   if($order == 'desc')
   // order the array from highest to lowest
}

Solution

  • Check the usort function

    function cmp($a, $b)
    {
        if ($a == $b) {
            return 0;
        }
        return ($a < $b) ? -1 : 1;
    }
    
    $a = array(3, 2, 5, 6, 1);
    
    usort($a, "cmp");