简体   繁体   English

使用不同类型的索引对多维数组进行排序

[英]sort multidimensional array with different types of index

I'm really confused about sorting multidimensional arrays in PHP. 我真的对在PHP中对多维数组进行排序感到困惑。 I do have an array like: 我确实有一个像这样的数组:

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"

  }
}

for my application I need to order these 5 arrays by the including "price" values from low to high. 对于我的应用程序,我需要按从低到高的“价格”值对这5个数组进行排序。 I already tried lots of functions mentioned at php documentation but didn't find any working solution. 我已经尝试了php文档中提到的许多功能,但是没有找到任何有效的解决方案。 Do you have any ideas? 你有什么想法? I really got stuck at this. 我真的被这个困住了。

Thanks for your replies. 多谢您的回覆。

You want uasort (which sort assoc arrays by a user-specified function.). 您需要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)...

You could also dump everything into a more simple array, an use usort but there are some additional steps, since you need to flatten it first.. 您还可以将所有内容转储到一个更简单的数组中,使用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) ...

You said you tried the functions at php.net. 您说您在php.net上尝试了这些功能。 Are you sure ksort won't work? 您确定ksort无法正常工作吗? http://us3.php.net/ksort http://us3.php.net/ksort

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM