2014-02-16 31 views
0

我對使用PHP排序多維數組非常困惑。我有喜歡的數組:使用不同類型的索引對多維數組進行排序

array(5) { 
    ["DH"]=> 
    array(3) { 
    ["price"]=> 
    string(5) "19.99" 
    ["merchant"]=> 
    string(16) "DH" 

    } 
    ["17.36"]=> 
    array(6) { 
    ["price"]=> 
    string(5) "17.36" 
    ["merchant"]=> 
    string(8) "Merchant" 
    ["rating"]=> 
    string(6) "95-97%" 
    ["reviews"]=> 
    string(5) "16990" 
    ["time"]=> 
    string(19) "2014-02-12 17:07:02" 

    } 
    ["hug"]=> 
    array(3) { 
    ["price"]=> 
    string(5) "19.99" 
    ["merchant"]=> 
    string(16) "hug" 

    } 
    ["22.95"]=> 
    array(6) { 
    ["price"]=> 
    string(5) "22.95" 
    ["merchant"]=> 
    string(8) "Merchant" 
    ["rating"]=> 
    string(7) "98-100%" 
    ["reviews"]=> 
    string(5) "61043" 
    ["time"]=> 
    string(19) "2014-02-12 17:07:02" 

    } 
    ["24.05"]=> 
    array(6) { 
    ["price"]=> 
    string(5) "24.05" 
    ["merchant"]=> 
    string(8) "Merchant" 
    ["rating"]=> 
    string(6) "90-94%" 
    ["reviews"]=> 
    string(4) "8754" 
    ["time"]=> 
    string(19) "2014-02-12 17:07:02" 

    } 
} 

爲我的應用程序需要通過包括「價格」值來訂購這些5個陣列由低到高。我已經嘗試了很多php documentation提到的功能,但沒有找到任何工作解決方案。你有什麼想法?我真的被困在這。

感謝您的回覆。

回答

0

你想要uasort(它通過用戶指定的函數對數組進行排序)。

function sortByPrice($a, $b) 
{ 
    return floatval($b['price']) - floatval($a['price']); 
} 
uasort($assoc, 'sortByPrice'); 


// Keys are intact, but associative array is sorted. 
foreach ($assoc as $key=>$value)... 

你也可以放棄一切成更簡單的陣列,使用usort但也有一些額外的步驟,因爲你需要首先拼合吧..

$out = array(); 
function sortByPriceSimple($a, $b) 
{ 
    return floatval($b) - floatval($a); 
} 
foreach ($assoc as $value) 
{ 
    $out[] = $value; 
} 
usort($out, 'sortByPriceSimple'); 

// This will be an indexed (0 to N) array. 
foreach ($out as $index=>$value) ... 
+0

謝謝,這很好:) –

+0

然後標記它是正確的。 :) –

-1

你說你試過功能在php.net。你確定ksort不會工作嗎? http://us3.php.net/ksort

+0

ksort按鍵排序,而不是按字段排序。 –

+0

是的,我的錯誤,只看到了關鍵的值。一個http://us3.php.net/uasort會給你靈活性。你可以定義它的排序方式。因此,如果密鑰不是有效的價格,請使用子元素的價格值。或者在數組中搜索與特定格式匹配的值並將其推入另一個數組。約翰也打敗了我:P – Darius

相關問題