[英]sort multidimensional array with different types of index
我真的對在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文檔中提到的許多功能,但是沒有找到任何有效的解決方案。 你有什么想法? 我真的被這個困住了。
多謝您的回覆。
您需要uasort (通過用戶指定的函數對assoc數組進行排序)。
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) ...
您說您在php.net上嘗試了這些功能。 您確定ksort無法正常工作嗎? http://us3.php.net/ksort
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.