Yes I know there are tons of questions like this. I want to re-order my array based on the 'magnitude' key in this array in descending order. I've been hovering all around the right method to use (array_multisort(), arsort(), etc.) but haven't figured out how to get exactly what I want.
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 )
The problem was...
It had to do with the array not being properly formatted. I had to take the results of a MySQL query and put them all into an array like so:
$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++;
}
After this, I needed a foreach loop to organize the $prefix_rows_arr:
foreach($prefix_rows_arr as $row){
$arr[] = $row;
}
Then finally the usort() worked as expected
function compareMagnitudes($a, $b){
if ($a['magnitude'] == $b['magnitude']) {
return 0;
}
return ($a['magnitude'] > $b['magnitude']) ? -1 : 1;
}
usort($arr, 'compareMagnitudes');