按值对多个字段排序多维数组php

阿格鲁斯

我有以下数组:

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;
}

尽管它确实按Brand对数组进行了排序,但根据我当前所处的站点,它并不能解决问题

在此先感谢您的帮助!

凯文

如果您需要一个针(或一个值)将其内部比较(导入)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;
});

样本输出

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章