如何按给定键的值对关联数组进行排序并在php中维护键? [复制]
Posted
技术标签:
【中文标题】如何按给定键的值对关联数组进行排序并在php中维护键? [复制]【英文标题】:How to sort associative arrays by value of a given key and maintain key in php? [duplicate] 【发布时间】:2016-05-17 18:06:41 【问题描述】:给定这个数组
$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】:$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);
【讨论】:
你能给我 Array ( [sdfsdfsdsx65fsdf1] => Array ( [type] => fruit [price] => 3.5 ) [sdfsdfsdsx65fsdf2] => Array ( [type] => milk [价格] => 2.9 ) [sdfsdfsdsx65fsdf3] => 数组 ( [类型] => 猪肉 [价格] => 5.43 ) ) 是的,你的输出是写的,但我已经编辑了问题,请检查一次,请给我一个输出以上是关于如何按给定键的值对关联数组进行排序并在php中维护键? [复制]的主要内容,如果未能解决你的问题,请参考以下文章