如何在 PHP 中按给定键的值对关联数组进行排序

在本文中,我们将讨论一个常见问题:如何使用 PHP 根据给定键的值对数组数组进行排序。

使用自定义比较函数

另一种选择是使用自定义比较函数。
这是一个非常快速和方便的解决方案。

这是示例:

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 根据给定键的值对数组进行排序的方法。

使用 array_multisort()

让我们看看如何使用 array_multisort() 函数:

$price = array(); 
foreach ($inventory as $key => $row) { 
$price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

在 PHP 5.5 及以上版本中,可以使用 array_column() 代替 foreach。

以下是如何做到这一点:

$price = array_column($inventory, 'price'); 
array_multisort($price, SORT_DESC, $inventory);
日期:2020-06-02 22:15:53 来源:oir作者:oir