简体   繁体   中英

sort multidimensional array with different types of index

I'm really confused about sorting multidimensional arrays in 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. I already tried lots of functions mentioned at php documentation but didn't find any working solution. 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.).

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..

$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. Are you sure ksort won't work? http://us3.php.net/ksort

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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