Skip to content

Instantly share code, notes, and snippets.

@lelotnk
Last active December 22, 2015 23:09
Show Gist options
  • Save lelotnk/6544868 to your computer and use it in GitHub Desktop.
Save lelotnk/6544868 to your computer and use it in GitHub Desktop.
Ordenação de strings.
<?php
// Criar uma lista de testes.
$array = array();
$letter ='A';
for ($i = 0; $i <= 1000; $i++) {
for ($j = 1; $j < 13; $j++) {
$array[] = $letter . $j;
}
$letter++;
}
shuffle($array); // Embaralhar para o teste.
// Ordenar
usort($array, function($a, $b) {
list($la, $na) = preg_split('#(\d+)$#', $a, 2, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
list($lb, $nb) = preg_split('#(\d+)$#', $b, 2, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if (strlen($la) < strlen($lb)) {
return -1;
} elseif (strlen($la) > strlen($lb)) {
return 1;
} else {
$strcmp = strcmp($la, $lb);
$intcmp = ($na == $nb) ? 0 : (($na < $nb) ? -1 : 1);
return ($strcmp == 0) ? $intcmp : $strcmp;
}
});
echo '<pre>';
print_r($array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment