Sorting array and adding position numbers while/after sorting

I have a pretty simple multidimensional array.

Array (
  [183] => Array (
    [info] => Array (
      [name] => Ben
      [points] => 4800
    )
  )

  [380] => Array (
    [info] => Array (
      [name] => Ruben
      [points] => 14500
    )
  )

  [450] => Array (
    [info] => Array (
      [name] => Alex
      [points] => 4800
    )
  )
)

I also have some PHP code. It sorts the array.

The first criteria is points which will be sorted descending. The second criteria is name which will be sorted ascending.

uasort($array, function($a, $b)
{
  if ($a['info']['points'] == $b['info']['points'])
  {
    return strcmp($a['info']['name'], $b['info']['name']);
  }

  return $b['info']['points'] - $a['info']['points'];
});

After my code does its job, the array looks like this:

Array (
  [380] => Array (
    [info] => Array (
      [name] => Ruben
      [points] => 14500
    )
  )

  [450] => Array (
    [info] => Array (
      [name] => Alex
      [points] => 4800
    )
  )

  [183] => Array (
    [info] => Array (
      [name] => Ben
      [points] => 4800
    )
  )
)

Sorting goes just fine, but I also would like to add position numbers while sorting the array.

In other words, if the points are better, the position is better. If the points are equal, the position must be equal.

The final array should look like this:

Array (
  [380] => Array (
    [info] => Array (
      [name] => Ruben
      [points] => 14500
      [position] => 1
    )
  )

  [450] => Array (
    [info] => Array (
      [name] => Alex
      [points] => 4800
      [position] => 2 /* because Alex has less points than Ruben */
    )
  )

  [183] => Array (
    [info] => Array (
      [name] => Ben
      [points] => 4800
      [position] => 2 /* because Ben has same points with Alex */
    )
  )
)

So, how could I add those position numbers? The faster way, the better way.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.