给定这个数组:
$inventory = array(
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
array("type"=>"pork", "price"=>5.43),
);
我想按价格排序$inventory的元素,以获得:
$inventory = array(
array("type"=>"pork", "price"=>5.43),
array("type"=>"fruit", "price"=>3.50),
array("type"=>"milk", "price"=>2.90),
);
我该怎么做呢?
虽然其他人正确地建议使用array_multisort(),但由于某种原因,似乎没有答案承认array_column()的存在,它可以极大地简化解决方案。所以我的建议是:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
如果你想对字符串进行不区分大小写排序,你可以使用SORT_NATURAL|SORT_FLAG_CASE
array_multisort(array_column($inventory, 'key_name'), SORT_DESC, SORT_NATURAL|SORT_FLAG_CASE, $inventory);
因为数组元素本身就是带有字符串键的数组,所以最好定义一个自定义比较函数。做起来又快又简单。试试这个:
function invenDescSort($item1,$item2)
{
if ($item1['price'] == $item2['price']) return 0;
return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);
产生以下结果:
Array
(
[0] => Array
(
[type] => pork
[price] => 5.43
)
[1] => Array
(
[type] => fruit
[price] => 3.5
)
[2] => Array
(
[type] => milk
[price] => 2.9
)
)
从PHP 7.4开始,你可以使用arrow函数:
usort(
$inventory,
fn(array $a, array $b): int => $b['price'] <=> $a['price']
);
代码(演示):
$inventory = [
['type' => 'fruit', 'price' => 3.50],
['type' => 'milk', 'price' => 2.90],
['type' => 'pork', 'price' => 5.43],
];
usort(
$inventory,
fn(array $a, array $b): int => $b['price'] <=> $a['price']
);
print_r($inventory);
(浓缩)输出:
Array
(
[0] => Array ([type] => pork, [price] => 5.43)
[1] => Array ([type] => fruit, [price] => 3.5)
[2] => Array ([type] => milk, [price] => 2.9)
)