具有键值的多维数组排序

时间:2017-04-11 07:28:41

标签: php arrays sorting

我在PHP中有这样的数组。我按金额升序订购了什么:

Array
(
    [0] => Array
        (
            [trans_id] => PR58EC68AFE8B0F3186
            [bill_number] => 1
            [order_date] => 2017-04-11
            [amount] => 800
            [trx_type] => purchase
        )

    [1] => Array
        (
            [trans_id] => PR58EC68AFE8B0F3186
            [bill_number] => 1
            [order_date] => 2017-04-11
            [amount] => 150
            [trx_type] => purchase-paid
        )

    [2] => Array
        (
            [trans_id] => PR58EC68AFE8B0F3186
            [bill_number] => 1
            [order_date] => 2017-04-11
            [amount] => 100
            [trx_type] => purchase-paid
        )

    [3] => Array
        (
            [trans_id] => BL58EC68EC4BCA18805
            [bill_number] => 1
            [order_date] => 2017-04-11
            [amount] => 2000
            [trx_type] => bill
        )

1 个答案:

答案 0 :(得分:1)

您可以使用usort()内置函数与您的自定义函数

    <?php
$yourarray = array(
    0 => array(
        'bill_number' => 3,
        'amount' => 100
    ),
    1 => array(
        'bill_number' => 4,
        'amount' => 50
    ),
    2 => array(
        'bill_number' => 5,
        'amount' => 150
    ),
);

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

usort($yourarray, 'sortByOrder');
echo "<pre>";
print_r($yourarray);
?>

然后输出

Array
(
    [0] => Array
        (
            [bill_number] => 4
            [amount] => 50
        )

    [1] => Array
        (
            [bill_number] => 3
            [amount] => 100
        )

    [2] => Array
        (
            [bill_number] => 5
            [amount] => 150
        )

)

了解更多信息

http://php.net/manual/en/function.usort.php