开发者

Sorting a multi-array by the inner value

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
        开发者_StackOverflow)

)

[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


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");


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.


This should be sufficient:

uasort($yourArray,
       create_function('$a,$b','return $a[0]["sort_order"] > $b[0]["sort_order"];'));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜