0

I have this array and I want to sort it (ASC)?

$stand_array[$player_name][$player_points] = $player_rank;

print_r

Array
(
[Player1] => Array
    (
        [50] => 5.7
    )

[Player2] => Array
    (
        [40] => 4.2
    )

[Player3] => Array
    (
        [30] => 3.7
    )

[Player4] => Array
    (
        [20] => 2.3
    )

[Player5] => Array
    (
        [10 => 1.5
    )

[Player6] => Array
    (
        [60] => 6.3
    )
)

Would you like to help me to solve this array on $player_rank (ASC)?

NB: I tried this function, but it did not work:

function sortByOrder($a, $b) {
    return $a[$player_rank] - $b[$player_rank];
}
usort($myArray, 'sortByOrder');
2
  • Did you use sql to generate the array? or what did you used to Commented Feb 5, 2016 at 23:55
  • I did not generate it with sql otherwise would be easy to sort it. I created the array stand_array with array $player_points and array $player_rank Commented Feb 5, 2016 at 23:58

1 Answer 1

1

The variable $player_rank is not visible from the sortByOrder function scope. Also, the indexes is different in each player array, so you need to access it like this:

function sortByOrder($a, $b) 
{ 
    $a = end($a);
    $b = end($b);

    if ($a == $b) 
    {
       return 0;
    }

    return ($a < $b) ? -1 : 1;
}
usort($myArray, 'sortByOrder');

And if you want to save keys in $myArray then you must use the uasort function instead of usort.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.