I have a multidimensional array and I want to sort based off the 'rating'... but I also want the index to start at 1 which is what I used when manually creating these. When I use usort it rearranges the array but now they start at index 0 so I can't do a loop from 1 - 6 because 6 is undefined after sort.
It was cleaner to start my $array at 1 so $player[$i] represented that actual player number. Here's what my array looks like before sort
$player[1]['rating'] = 8
$player[2]['rating'] = 5
$player[3]['rating'] = 10
Here's my sort function:
function sortByrating($a, $b) {
if ($a['rating'] == $b['rating']) {
return 0;
}
return ($a['rating'] < $b['rating']) ? -1 : 1;
}
And I call it by
usort($player, 'sortByRating');
1should still have key1after sorting, but that key may be sorted elsewhere? In that case you should be usinguasort. – Otherwise, if the1is just used for outputting "1.", you should not bend over backwards here; arrays are zero-indexed, period, add+ 1for visual output when needed.foreach()loop or start yourfor()loop from 0.