0

i have this array

[Computers] => Array
(
    [0] => Array
        (
            [product_id] => 78
            [category_name] => Computers
            [sort_order] => 1
        )

    [1] => Array
        (
            [product_id] => 70
            [category_name] => Computers
            [sort_order] => 1
        )

)


[Scanners] => Array
(
    [0] => Array
        (
            [product_id] => 65
            [category_name] => Scanners
            [sort_order] => 6
        )

)

[Printers] => Array
(
    [0] => Array
        (
            [product_id] => 58
            [category_name] => Printers
            [sort_order] => 3
        )

)
[Screens] => Array
(
    [0] => Array
        (
            [product_id] => 62
            [category_name] => Screens
            [sort_order] => 2
        )

)

I cant seem to find a way to sort the array based on the key sort_order. I tried all the examples from here but no luck. I need the arrays in this order

Computers
Screens
Printers
Scanners
Community
  • 1
  • 1
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
  • possible duplicate of [PHP sort multidimensional array by value](http://stackoverflow.com/questions/2699086/php-sort-multidimensional-array-by-value) – hakre Jun 22 '11 at 18:34
  • If you look at my question I clearly state that I have tried all these solutions with no luck because there are internal arrays in my question – Matt Elhotiby Jun 22 '11 at 18:36
  • So your actual problem is how to adopt the answers from the other question for your data? – hakre Jun 22 '11 at 18:37
  • Can you show what the finally array should be? – Rob Jun 22 '11 at 18:41

3 Answers3

1

try this out

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);

    foreach ($array as $ii => $va) {
            foreach ($array[$ii] as $i => $val) {
                $sorter[$ii]=$val[$key];
            }
    }
    asort($sorter);
    foreach ($sorter as $element => $value) {
        $ret[$element]=$array[$element];
    }
    $array=$ret;
}

 aasort($array,"sort_order");
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321
1

You simply have the sort parameter at the wrong level. You want to sort the highest level right? So put the sorting parameter there as well. The following data structure would make much more sense:

[Computers] => Array
(
    [sort_order] => 1,
    [data] => array(
        [0] => Array
            (
                [product_id] => 78,
                [category_name] => Computers,
                [sort_order] => 1,
            )
    )
)

If you nest the sort order as deep in the data structure as you have it will make for horrible sorting algorithms.

hoppa
  • 3,011
  • 18
  • 21
0

This should be sufficient:

uasort($yourArray,
       create_function('$a,$b','return $a[0]["sort_order"] > $b[0]["sort_order"];'));
Dr.Molle
  • 116,463
  • 16
  • 195
  • 201