While this may seem obvious, user-defined array sorting functions ( uksort(), uasort(), usort() ) will *not* be called if the array does not have *at least two values in it*.
The following code:
<?php
function usortTest($a, $b) {
var_dump($a);
var_dump($b);
return -1;
}
$test = array('val1');
usort($test, "usortTest");
$test2 = array('val2', 'val3');
usort($test2, "usortTest");
?>
Will output:
string(4) "val3"
string(4) "val2"
The first array doesn't get sent to the function.
Please, under no circumstance, place any logic that modifies values, or applies non-sorting business logic in these functions as they will not always be executed.
Ordenando Arrays
O PHP tem muitas funções para lidar com ordenação de arrays, e esse documento existe para ajudar a você lidar com elas.
As principais diferenças são:
- Algumas ordenam com base nas chaves do array, enquanto outras pelos valores: $array['chave'] = 'valor';
- A correlação entre as chaves e os valores do array não são mantidas depois da ordenação, o que pode fazer com que as chaves sejam resetadas numericamente (0, 1, 2, ...)
- A ordem da ordenação: alfabética, menor para maior (ascendente), maior para menor (descendente), numérica, natural, aleatório, ou definida pelo usuário
- Nota: Todas essas funções agem diretamente na própria variável do array, ao invés de retornar um novo array ordenado
- Se qualquer uma dessas funções avaliar dois membros como iguais então a ordem será indefinida (a ordenação não é estável).
| Nome da função | Ordena por | Mantém a associação de chaves | Ordem da ordenação | Funções relacionadas |
|---|---|---|---|---|
| array_multisort() | valor | associativo sim, numérico não | primeiro array ou opções de ordenação | array_walk() |
| asort() | valor | sim | menor para maior | arsort() |
| arsort() | valor | sim | maior para menor | asort() |
| krsort() | chave | sim | maior para menor | ksort() |
| ksort() | chave | sim | menor para maior | asort() |
| natcasesort() | valor | sim | natural, não sensível a maiúsculas | natsort() |
| natsort() | valor | sim | natural | natcasesort() |
| rsort() | valor | não | maior para menor | sort() |
| shuffle() | valor | não | random | array_rand() |
| sort() | valor | não | menor para maior | rsort() |
| uasort() | valor | sim | definido pelo usuário | uksort() |
| uksort() | chave | sim | definido pelo usuário | uasort() |
| usort() | valor | não | definido pelo usuário | uasort() |
"Matthew Rice" ¶
7 days ago
oculiz at gmail dot com ¶
2 years ago
Another way to do a case case-insensitive sort by key would simply be:
<?php
uksort($array, 'strcasecmp');
?>
Since strcasecmp is already predefined in php it saves you the trouble to actually write the comparison function yourself.
Dirk ¶
3 years ago
If you need to perform any of these sort functions on an array containing two or more equivalent values, you can get the equivalents to fall next to each other within the overall ordering (similar to how MySQL's ORDER BY works...) instead of breaking the sort() function, by using ksort() as a second parameter to arbitrarily distinguish any equivalent values by their unique keys:
<?php
sort($array, ksort($array));
?>
Seems like this effect should be built in. At least the workaround is so short...
K.i.n.g.d.r.e.a.d ¶
3 years ago
If you search a feature which sorts an array incasesensitive by key, try this:
<?php
function isort($a,$b) {
return strtolower($a)>strtolower($b);
}
uksort($array, "isort");
?>
