按内部值对多数组进行排序

时间:2011-06-22 18:32:21

标签: php arrays sorting multidimensional-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
        )

)

我似乎无法找到一种基于密钥sort_order对数组进行排序的方法。我尝试了here的所有例子,但没有运气。我按此顺序需要数组

Computers
Screens
Printers
Scanners

3 个答案:

答案 0 :(得分:1)

试试这个

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

答案 1 :(得分:1)

您只需将sort参数设置为错误的级别。你想排序最高级别吗?所以也把排序参数放在那里。以下数据结构将更有意义:

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

如果您将排序顺序嵌套在数据结构的深处,那么它将会产生可怕的排序算法。

答案 2 :(得分:0)

这应该足够了:

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