如何按给定键的值对关联数组进行排序并在php中维护键?

时间:2016-02-08 06:24:00

标签: php arrays

给定这个数组

$inventory = array(
    "sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50),
    "sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90),
    "sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43)
);

我想要输出如下

$inventory = array(
    "sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43),
    "sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50),
    "sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90)  
);

1 个答案:

答案 0 :(得分:1)

$inventory = array(
  array("sdfsdfsdsx65fsdf1"=>array("type"=>"fruit", "price"=>3.50)),
  array("sdfsdfsdsx65fsdf2"=>array("type"=>"milk", "price"=>2.90)),
  array("sdfsdfsdsx65fsdf3"=>array("type"=>"pork", "price"=>5.43))
);

usort($inventory, function($a, $b) {
  foreach ($a as $a);
  foreach ($b as $b);
  if ($a['price'] == $b['price']) return 0;
  return ($a['price'] < $b['price']) ? 1 : -1;
});

print_r($inventory);