Wednesday, 29 August 2018

Sort a multidimensional array in PHP

Possible Duplicate:
PHP - Multiple uasort functions breaks sorting
I have multidimensional array in php with 3 columns.I needs to sort it by "awarded_units" and if two users have same awarded_units(tiebreaker), then one with least selected unit will come first.
user_id awarded_units selected_units

15       5               2
22       5               1
3        4               2
4        4               5
5        4               1

As you see, I had already sorted array on the basis of awarded_units using some multidimensional sort function. Now, I needs to resolve the tiebreaker condition . Since user_id=15 and user_id=22 have same awarded_units so user_id 22 must come first.
Correct order will be
user_id awarded_units selected_units

22       5               1
15       5               2
5        4               1
3        4               2
4        4               5

Kindly tell me how to do this.Thanks

You can use array_multisort:
$cols = array();
foreach ($multiArray as $key => $value)
{
    $cols['awarded_units'][$key]  = $value['awarded_units'];
    $cols['selected_units'][$key] = $value['selected_units'];
}
array_multisort($cols['awarded_units'], SORT_DESC, $cols['selected_units'], SORT_ASC, $multiArray);

0 comments:

Post a Comment