我有以下数组结构:
Array ( [0] => Array ( [configuration_id] => 10 [id] => 1 [optionNumber] => 3 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) [1] => Array ( [configuration_id] => 9 [id] => 1 [optionNumber] => 2 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) [2] => Array ( [configuration_id] => 8 [id] => 1 [optionNumber] => 1 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) )
基于,以增量方式对数组进行排序的最佳方法是optionNumber什么?
optionNumber
因此结果如下所示:
Array ( [0] => Array ( [configuration_id] => 8 [id] => 1 [optionNumber] => 1 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) [1] => Array ( [configuration_id] => 9 [id] => 1 [optionNumber] => 2 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) [2] => Array ( [configuration_id] => 10 [id] => 1 [optionNumber] => 3 [optionActive] => 1 [lastUpdated] => 2010-03-17 15:44:12 ) )
使用usort。
usort
function cmp_by_optionNumber($a, $b) { return $a["optionNumber"] - $b["optionNumber"]; } ... usort($array, "cmp_by_optionNumber");
在PHP≥5.3中,应改为使用匿名函数:
usort($array, function ($a, $b) { return $a['optionNumber'] - $b['optionNumber']; });
请注意,以上两个代码均假定$a['optionNumber']为整数。
$a['optionNumber']
在PHP≥7.0,使用<=>,而不是减法,以防止溢出/截断问题。
<=>
usort($array, function ($a, $b) { return $a['optionNumber'] <=> $b['optionNumber']; });