Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort the rows of a 2d array by column [duplicate]

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]

like image 983
betus Avatar asked Dec 11 '25 18:12

betus


1 Answers

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');
like image 141
Naftali Avatar answered Dec 14 '25 08:12

Naftali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!