Sort array by key, being a string

3

I have a random array containing an alphanumeric sequence in its keys. Using the ksort function, I get the following result:

array(22) {
  ["A1"]=>
  string(2) "A1"
  ["A10"]=>
  string(3) "A10"
  ["A11"]=>
  string(3) "A11"
  ["A12"]=>
  string(3) "A12"
  ["A2"]=>
  string(2) "A2"
  ["A4"]=>
  string(2) "A4"
  ["A5"]=>
  string(2) "A5"
}

However, ordering must prioritize the numerical order of the keys. The expected result is:

array(22) {
  ["A1"]=>
  string(2) "A1"
  ["A2"]=>
  string(3) "A2"
  ["A4"]=>
  string(2) "A4"
  ["A5"]=>
  string(2) "A5"
  ["A10"]=>
  string(2) "A10"
  ["A11"]=>
  string(3) "A11"
  ["A12"]=>
  string(3) "A12"
}
    
asked by anonymous 08.10.2015 / 16:32

2 answers

5

You need to sort the keys using the natural sort algorithm. See the example below:

<?php
$dados = [
    'A1'=> 'A1',
    'A10'=> 'A10',
    'A11'=> 'A11',
    'A12'=> 'A12',
    'A2'=> 'A2',
    'A4'=> 'A4',
    'A5'=> 'A5',
];

uksort($dados, 'strnatcmp');
var_dump($dados);
?>
    
08.10.2015 / 17:07
1

Code

$sort = array(
    "A1"    =>  "A1",
    "A10"   =>  "A10",
    "A11"   =>  "A11",
    "A12"   =>  "A12",
    "A2"    =>  "A2",
    "A4"    =>  "A4",
    "A5"    =>  "A5",
    "C12"   =>  "C12",
    "C1"    =>  "C1",
    "B7"    =>  "B7",
    "C52"   =>  "C52",
    "C5"    =>  "C5",
    "B12"   =>  "B12",
);
ksort($sort); // Ordena o array por string

$sortNumber = array();
foreach ($sort as $key => $value){       // quebra o array em bidimencional separando letras de numeros
    $string = preg_replace('~[^a-z]~i', '', $key);
    $number = preg_replace('~\D~', '', $key);

    $sortNumber[$string][$number] = $value;
}

$newArray = array(); 
foreach ($sortNumber as $letter => $options) {  
    ksort($options); // ordena a parte numerica
    foreach ($options as $number => $value) {
        $newArray["{$letter}{$number}"] = $value; // cria novamente o array ordenado por letras e numeros
    }
}

Out

Array
(
    [A1] => A1
    [A2] => A2
    [A4] => A4
    [A5] => A5
    [A10] => A10
    [A11] => A11
    [A12] => A12
    [B7] => B7
    [B12] => B12
    [C1] => C1
    [C5] => C5
    [C12] => C12
    [C52] => C52
)

OBS

There may be faults if the key is made up of letters and numbers and these are mixed. Ex: A12C8 .

    
08.10.2015 / 16:56