简体   繁体   English

PHP阵列按数据库的评分结果排序

[英]PHP array sorting by scored results from database

I have an array that I'm simply trying to order by a score key that contains the value that I'm trying to sort by. 我有一个数组,我只是想按一个score键排序,该score键包含我要按其排序的值。 The desired results would change the order of the array below to display the index in the following order: [0] , [2] , [1] . 所需的结果将更改下面的数组的顺序,以按以下顺序显示索引: [0][2][1]

I'm looping through the results which are pulled from a database. 我正在遍历从数据库中提取的结果。 I'm creating a key named score and then pushing the $row2 array in to a separate array because if I use mysql_data_seek it gets rid of the score key. 我正在创建一个名为score的键,然后将$row2数组推入一个单独的数组中,因为如果使用mysql_data_seek它将摆脱score键。

Also it's creating an unwanted key score at the bottom. 另外,它还在底部创建了不必要的关键score

How can I best clean this up and make sure the results are ordered high to low as desired? 如何最好地清理并确保结果按需要从高到低排序?

$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);
}

Current undesired results... 当前的不良结果...

Array
(
    [0] => Array
        (
            [score] => 7
        )
    [1] => Array
        (
            [score] => 2
        )
    [2] => Array
        (
            [score] => 4
        )
    [score] => 
)

Desired results... 所需的结果...

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');

on php>5.3 you can use inline-functoins: 在php> 5.3上,您可以使用inline-functoins:

usort(&$myArray, function($a,$b){ /* ... */ });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM