2017-05-26 74 views
2

我有以下阵列:排序多维数组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; 
} 

虽然它不排序按品牌的阵列,它不取决于我目前在

哪个网站做的伎俩

预先感谢您的帮助!

回答

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

Sample Output

+0

这个工作做得非常好!非常感谢您的先生! – Agrus

+0

@Agrus当然很高兴这个帮助 – Ghost

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

相关信息:http://php.net/array_multisort

+1

好的。我喜欢它.. +1 –

+0

感谢@SahilGulati – gvgvgvijayan

+0

虽然这类型的数组正确的,它并没有解决,如果我对品牌3的网站,它应该首先出现,不会持续太久:( – Agrus