基于值的PHP排序数组

时间:2015-03-19 17:12:47

标签: php arrays sorting

是的,我知道有很多像这样的问题。我想根据此数组中的“magnitude”键按降序重新排序我的数组。我一直在使用正确的方法(array_multisort(),arsort()等),但还没弄明白如何得到我想要的东西。

Array ( [alCrn] => 27113 [epcid] => IMC601 [last_access] => 2015-03-14 15:26:40 [magnitude] => 1 ) 
Array ( [alCrn] => 27114 [epcid] => IMC602 [last_access] => 2015-03-16 20:45:17 [magnitude] => 8 ) 
Array ( [alCrn] => 27115 [epcid] => IMC603 [last_access] => 2015-03-15 17:57:58 [magnitude] => 2 ) 
Array ( [alCrn] => 27120 [epcid] => IMC608 [last_access] => 2015-03-15 23:56:16 [magnitude] => 12 ) 
Array ( [alCrn] => 27122 [epcid] => IMC612 [last_access] => 2015-03-15 19:55:02 [magnitude] => 2 ) 
Array ( [alCrn] => 27123 [epcid] => IMC615 [last_access] => 2015-03-17 14:00:34 [magnitude] => 6 )

问题是......

这与数组格式不正确有关。我不得不接受MySQL查询的结果并将它们全部放入一个数组中,如下所示:

$count = 0;
while($prefix_rows = $prefix_results->fetch_assoc()){
    //the results are not yet ordered according to the number of clicks...save each row in an array and sort using php in next step
    $prefix_rows_arr[$count]['alCrn'] = $prefix_rows['alCrn'];
    $prefix_rows_arr[$count]['epcid'] = $prefix_rows['epcid'];
    $prefix_rows_arr[$count]['last_access'] = $prefix_rows['last_access'];
    $prefix_rows_arr[$count]['magnitude'] = $prefix_rows['magnitude'];

    $count++;               
}

在此之后,我需要一个foreach循环来组织$ prefix_rows_arr:

foreach($prefix_rows_arr as $row){
    $arr[] = $row;
}

然后最后usort()按预期工作

function compareMagnitudes($a, $b){
    if ($a['magnitude'] == $b['magnitude']) {
        return 0;
    }
    return ($a['magnitude'] > $b['magnitude']) ? -1 : 1;    
}
usort($arr, 'compareMagnitudes');

1 个答案:

答案 0 :(得分:1)

您可以定义一个比较函数,并将其作为第二个参数传递给usort函数,该函数按降序对数组进行排序。

function cmp($a, $b) {
    if ($a['key'] == $b['key']) {
        return 0;
    }
    return ($a['key'] < $b['key']) ? -1 : 1;
}

usort($your_array, "cmp");

将比较函数中的key替换为适当的值,magnitude