通过多个具有值的字段对多维数组php进行排序

时间:2017-05-26 08:58:22

标签: php arrays sorting

我有以下数组:

Array
(
[3698] => Array
    (
        [brand] => Brand 1
        [rate] => 198
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1805] => Array
    (
        [brand] => Brand 2
        [rate] => 200,6
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1801] => Array
    (
        [brand] => Brand 3
        [rate] => 202,5
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1810] => Array
    (
        [brand] => Brand 1
        [rate] => 172
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )
)

我希望它首先按品牌排序,然后按费率排序,如下所示:

Array
(
[3698] => Array
    (
        [brand] => Brand 1
        [rate] => 172
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1810] => Array
    (
        [brand] => Brand 1
        [rate] => 198
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1805] => Array
    (
        [brand] => Brand 2
        [rate] => 202,5
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )

[1801] => Array
    (
        [brand] => Brand 1
        [rate] => 172
        [availability] => 0
        [stopsales] => 0
        [conditions] => 1
        [currencycode] => 1
    )
)

我已按照"品牌"排序但它按字母顺序排列,这并不是我所需要的。 "品牌"的方式应排序如下:

如果我在品牌2的网站上首先出现,如果我在品牌3中出现,那么它应首先出现,依此类推。

目前,我正在使用具有以下功能的uasort:

function sortByBrandName($a, $b) {
//global $hotelBrand;
$brandName = strcmp($a['brand'], $b['brand']);
if($brandName === 0)
{
    return $brandName;
}
return $brandName;
}

虽然它按照品牌对数组进行排序,但根据我目前在哪个网站

,它并没有做到这一点。

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

如果您需要针(或值)将uasort内的uasort进行比较(导入)到您的use,只需使用$hotelBrand = 'Brand 3'; uasort($data, function ($a, $b) use ($hotelBrand) { $a1 = levenshtein($hotelBrand, $a['brand']); $b1 = levenshtein($hotelBrand, $b['brand']); if ($a1 === $b1) { // if same name sort by rate return $a['rate'] > $b['rate'] ? 1 : -1; } else if ($a1 != $b1) { return $a1 > $b1 ? 1 : -1; } return 0; }); 关键字以及您的匿名函数即可。因此,在您的情况下,您可以使用品牌名称以及排序。

简单示例:

eTag

Sample Output

答案 1 :(得分:0)

array_multisort(array_column($data, 'brand'),  SORT_ASC,
                array_column($data, 'rate'), SORT_ASC,
                $data);

供参考:http://php.net/array_multisort