我有一个数组,我只是想通过score
键对其进行排序,该键包含我要排序的值。所需的结果会更改下面数组的顺序,以按以下顺序显示索引:[0]
、[2]
、[1]
。
我正在循环浏览从数据库中提取的结果。我正在创建一个名为score
的键,然后将$row2
数组推入一个单独的数组,因为如果我使用mysql_data_seek
,它将去掉score
键。
它还在底部创建了一个不需要的密钥score
。
我如何才能最好地清理它,并确保结果按要求从高到低排序?
$my_array = array();
while ($row2 = mysql_fetch_assoc($result2))
{
//score determined here
//$row2['score'] = ...more math, variable is numeric, not a string
array_push($array_page,$row2);
}
当前不需要的结果。。。
Array
(
[0] => Array
(
[score] => 7
)
[1] => Array
(
[score] => 2
)
[2] => Array
(
[score] => 4
)
[score] =>
)
所需结果。。。
Array
(
[0] => Array
(
[score] => 7
)
[2] => Array
(
[score] => 4
)
[1] => Array
(
[score] => 2
)
)
function scoreSort($a, $b){
if($a['score'] == $b['score']) return 0;
return $a['score'] > $b['score'] ? -1 : 1;
}
usort(&$myArray, 'scoreSort');
在php>5.3上,您可以使用内联函数:
usort(&$myArray, function($a,$b){ /* ... */ });