Multi-dimensional Array sort by value in php

Suppose we have a array like

Array
(
    [0] => Array
        (
            [color] => Green
            [order] => 13
        )

    [1] => Array
        (
            [color] => Black
            [order] => 2
        )

    [2] => Array
        (
            [color] => White
            [order] => 10
        )
)

This type of array sort by value easily using following algorithm.

For ascending :

function asc_sort (&$array, $key) {
    $sorter = array();
    $ret = array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii] = $va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii] = $array[$ii];
    }
    $array = $ret;
}
asc_sort($a_array, "color");

For descending :

function desc_sort (&$array, $key) {
    $sorter = array();
    $ret = array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii] = $va[$key];
    }
    arsort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii] = $array[$ii];
    }
    $array = $ret;
}

desc_sort($a_array, "color");

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s