按键值排序关联多数组

时间:2015-04-28 19:04:24

标签: php arrays sorting

下面是我的数组,我想按照asc顺序按价格排序。

我在下面写了代码

Array
(
    [105493] => Array
        (
            [info] => Array
                (
                    [price] => $50.00
                    [hazmat] => Not Required
                )
        )

    [105494] => Array
        (
            [info] => Array
                (
                    [price] => $93.60
                    [hazmat] => Not Required
                )

        )

    [105495] => Array
        (
            [info] => Array
                (
                    [price] => $198.00
                    [hazmat] => Not Required
                )
        )

    [105496] => Array
        (
            [info] => Array
                (
                    [price] => $662.00
                    [hazmat] => Not Required
                )
        )
)

我在代码下面对它进行排序

function customer_sort ($a, $b) {

    if ($a['info']['price'] == $b['info']['price']) {
        return 0;
    }
    return $a['info']['price'] > $b['info']['price'] ? 1 : -1;
}
uasort($assc_product_data, 'customer_sort');

但是我的代码不是很好,我怎么解决问题

1 个答案:

答案 0 :(得分:2)

在比较价格之前,您需要删除$

function customer_sort($a, $b)
    if ($a['info']['price'] == $b['info']['price']) {
        return 0;
    }
    return substr($a['info']['price'], 1) > substr($b['info']['price'], 1) ? 1 : -1;
}

您还可以使用内置函数strnatcmp

function customer_sort($a, $b) {
    return strnatcmp($a['info']['price'], $b['info']['price']);
}