2017-05-26 73 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