按键在php中的值排序数组

时间:2014-11-22 08:06:54

标签: php

我是php的新手,我完全不知道数组排序。问题是我需要对下面列出的数组taht进行排序,以按其关键字段order排序。意味着需要按照' 1,2,5'。

排序

数组:

Array
(
    [Apple] => Array
        (
            [name] => Apparel & Accessories                 
            [order] => 5
        )

    [Bannana] => Array
        (
            [name] => Business Stationary
            [order] => 1
        )

    [Orenge] => Array
        (
            [name] => Business Cards
            [order] => 2
        )

)

如何按Order排序此数组?

显示如::

Array
    (
        [Bannana] => Array
            (
                [name] => Business Stationary                   
                [order] => 1
            )

        [Orenge] => Array
            (
                [name] => Business Cards
                [order] => 2
            )

        [apple] => Array
            (
                [name] => Apparel & Accessories 
                [order] => 5
            )

    )

3 个答案:

答案 0 :(得分:2)

这应该适合你:

<?php

    $array = array(
                "Apple" => array(
                        "name" => "Apparel & Accessories",                 
                        "order" => 5
                    ),

                "Bannana" => array(
                        "name" => "Business Stationary",
                        "order" => 1
                    ),

                "Orenge" => array (
                        "name" => "Business Cards",
                        "order" => 2
                    )

            );


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

    usort($array, 'sortByOrder');   


    print_r($array);

?>

输出:

    Array
(
    [0] => Array
        (
            [name] => Business Stationary
            [order] => 1
        )

    [1] => Array
        (
            [name] => Business Cards
            [order] => 2
        )

    [2] => Array
        (
            [name] => Apparel & Accessories
            [order] => 5
        )

)

答案 1 :(得分:1)

建议您使用usort()。例如:

$arr = array
(
    "Apple" => array
    (
        "name" => "Apparel & Accessories" ,
        "order" => 5
    ),

    "Bannana" => array
    (
        "name" => "Business Stationary",
        "order" => 1
    ),

    "Orenge" => array
    (
        "name" => "Business Cards",
        "order" => 2
    )

);


function custom_sort($a, $b)
{
    if ($a['order']==$b['order']) return 0;
    return ($a['order'] < $b['order']) ? -1 : 1;
}

usort($arr, "custom_sort");

print '<pre>';
print_r($arr);
print '</pre>';

答案 2 :(得分:1)

Usort功能来了!

function sortbyorder($a, $b) {
    if ($a['order'] > $b['order']) return true; 
    else return false;
}
usort ($array, 'sortbyorder');

此处提供更多信息:http://php.net/manual/en/function.usort.php 最好的问候。

它也可以是:

function sortbyorder($a, $b) {
    return $a['order'] > $b['order']; 
}
usort ($array, 'sortbyorder');