phparrayssortingmultidimensional-array

Sort the rows of a 2d array by column


I would like to order this multi-dimensional array items[] by the key 'rel'.

print_r ($items) will output:

 Array(

 [36] => Array
    (
        [id] => 36
        [name] => mp4
        [total_items] => 58
        [rel] => 5.3015
    )

[61] => Array
    (
        [id] => 61
        [name] => mp3
        [total_items] => 61
        [rel] => 21.7269
    )

[63] => Array
    (
        [id] => 63
        [name] => avi
        [total_items] => 43
        [rel] => 2.254
    )
 )

and I need the rows to be: first [61] second [36] and then [63]


Solution

  • Here is what I use:

    function array_sort(&$array, $on, $order=SORT_ASC)
    {
        $new_array = array();
        $sortable_array = array();
    
        if (count($array) > 0) {
            foreach ($array as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $on) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }
    
            switch ($order) {
                case SORT_ASC:
                    asort($sortable_array);
                break;
                case SORT_DESC:
                    arsort($sortable_array);
                break;
            }
    
            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $array[$k];
            }
        }
    
        return $new_array;
    }
    

    So you would use it like this:

    array_sort($items, 'rel');