Monday, June 11, 2012

PHP sort multidimensional array by value


How can I sort this array by the value of the "order" key? Even though the values are currently sequential, they will not always be.




Array
(
[0] => Array
(
[hashtag] => a7e87329b5eab8578f4f1098a152d6f4
[title] => Flower
[order] => 3
)

[1] => Array
(
[hashtag] => b24ce0cd392a5b0b8dedc66c25213594
[title] => Free
[order] => 2
)

[2] => Array
(
[hashtag] => e7d31fc0602fb2ede144d18cdffd816b
[title] => Ready
[order] => 1
)
)


Source: Tips4all

5 comments:

  1. function aasort (&$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;
    }

    aasort($your_array,"order");

    ReplyDelete
  2. Try a usort: If you don't have access to anonymous functions yet (Before PHP 5.3), you'll have to define a sorting function first:

    function sortByOrder($a, $b) {
    return $a['order'] - $b['order'];
    }

    usort($myArray, 'sortByOrder');

    ReplyDelete
  3. I use this function :

    function array_sort_by_column(&$arr, $col, $dir = SORT_ASC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
    $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
    }


    array_sort_by_column($array, 'order');

    ReplyDelete
  4. I usually use usort, and pass my own comparison function. In this case, it is very simple:

    function compareOrder($a, $b)
    {
    return $a['order'] - $b['order'];
    }

    usort($array, 'compareOrder');

    ReplyDelete
  5. $sort = array();
    $array_lowercase = array_map('strtolower', $array_to_be_sorted);
    array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $alphabetically_ordered_array);


    This takes care of both upper and lower case alphabets.

    ReplyDelete