i have this enormous array that i am pulling from an API for BattleField Bad Company 2, and the soldier stats can be pulled as a multi dimensional array with an inner array
In addition to the other answers, if you need to sort by a dynamic field (only known at runtime), you can use an anonymous function and pass it the field via the use
keyword:
$field = "some_dynamic_value";
usort($rows, function($a, $b) use ($field) {
return strcmp($a[$field], $b[$field]);
});
You can use array_multisort for this: first provide the column you want to sort -- with array_column
and as second argument the whole array. There are several options possible (see documentation), but for an ascending sort by the "rank" field, it would look like this:
array_multisort(array_column($players, "rank"), $players);
NB: For the data in the actual question here, $players
would be &$arr["players"]
You can sort any array by any criteria using usort()
To order descending an array, I used
function sorterdesc($one, $two) {
return ($two['cont'] - $one['cont']);
}
For ascending :
function sorterasc($one, $two) {
return ($one['cont'] - $two['cont']);
}
Like this it works fine with numeric values
Here you go.
$playergoop is the array that you provided.
This one sorts by the sub-field 'rank', but it does so in an ascending order. If you want a descending order, you can switch the > to <.
function sorter($one, $two) {
return ($one['rank'] > $two['rank']);
}
usort($playergoop['players'], sorter);
When you're using PHP 5.3 and above you can use an anonymous inline function for sorting:
usort($obj, function ($a, $b)
{
return strcmp($a["name"], $b["name"]);
});