-1

I want to sort a table with hierarchical keys but I can not :( Here's an example:

array ( '1.1.1' => 'test1', '10.1.1' => 'test2', '2.1.1' => 'test3', 1 => 'test4', 2 => 'test5', 3 => 'test6', '0.1' => 'test7', 0 => 'test8', 10 => 'test9', )

The result must to be :

array ( '0' => 'test8', '0.1' => 'test7', '1' => 'test4', '1.1.1' => 'test1', '2' => 'test5', '2.1.1' => 'test3', '3' => 'test6',  '10' => 'test9', '10.1.1' => 'test2')

Thank a lot !

My attempt : https://notepad.pw/71vyf2f7

2 Answers2

1

Have you looked at uksort? http://php.net/manual/en/function.uksort.php

I think that's what you need

$arr = array ( '1.1.1' => 'test1', '10.1.1' => 'test2', '2.1.1' => 'test3', 1 => 'test4', 2 => 'test5', 3 => 'test6', '0.1' => 'test7', 0 => 'test8', 10 => 'test9', );



function cmp($a,$b) {
       return floatval($a) > floatval($b);
}

uksort($arr, 'cmp');

print_r($arr)
TommyBs
  • 9,354
  • 4
  • 34
  • 65
0
<?php

$in = [
    '1.1.1' => 'test1',
    '10.1.1' => 'test2', 
    '2.1.1' => 'test3', 
    1 => 'test4', 
    2 => 'test5', 
    3 => 'test6', 
    '0.1' => 'test7', 
    0 => 'test8', 
    10 => 'test9'
];
$desired = 
[
    '0' => 'test8', 
    '0.1' => 'test7', 
    '1' => 'test4', 
    '1.1.1' => 'test1', 
    '2' => 'test5', 
    '2.1.1' => 'test3', 
    '3' => 'test6', 
    '10' => 'test9', 
    '10.1.1' => 'test2'
];

ksort($in, SORT_NATURAL);
var_dump($in === $desired);
var_export($in);

Output:

bool(true)
array (
  0 => 'test8',
  '0.1' => 'test7',
  1 => 'test4',
  '1.1.1' => 'test1',
  2 => 'test5',
  '2.1.1' => 'test3',
  3 => 'test6',
  10 => 'test9',
  '10.1.1' => 'test2',
)
Progrock
  • 7,373
  • 1
  • 19
  • 25