0

Does anyone know how to correctly sort this array by version preserving the sub-arrays.

I have seen similar issues and solutions on stackoverflow but im not able to apply to my array.

Thanks in advance

array (size=3)
  '1.23.006' => 
    array (size=1)
      0 => string '1' (length=1)
  '2.0.0' => 
    array (size=1)
      0 => string '1' (length=1)
  '10.0.0' => 
    array (size=2)
      0 => string '1' (length=1)
      1 => string '4' (length=1)

I want it to be sorted like this:

array (size=3)
  '10.0.0' => 
    array (size=2)
      0 => string '1' (length=1)
      1 => string '4' (length=1)
  '2.0.0' => 
    array (size=1)
      0 => string '1' (length=1)
  '1.23.006' => 
    array (size=1)
      0 => string '1' (length=1)

1 Answers1

0

You need to use uksort to sort your array by keys, with a custom function that calls version_compare to compare them:

$data = array('1.23.006' => array('1'), '2.0.0' => array('1'), '10.0.0' => array('1', '4'));

uksort($data, function ($a, $b) {
    return version_compare($b, $a);
});

print_r($data);

Output:

Array
(
    [10.0.0] => Array
        (
            [0] => 1
            [1] => 4
        )
    [2.0.0] => Array
        (
            [0] => 1
        )
    [1.23.006] => Array
        (
            [0] => 1
        )
)

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95
  • But that code will fail if it is "10.0" instead of "10.0.0. " . I also have versions like "10.XX" – Fabián Fernández Aug 24 '20 at 04:11
  • @Fabian I can only answer the question you have asked. Please update the question with **all** the relevant information... – Nick Aug 24 '20 at 04:13
  • i want to sort the array by version. bigger to smaller... maybe this code can be applied to my array? but i dont understand it https://stackoverflow.com/a/48974986/14154823 – Fabián Fernández Aug 24 '20 at 04:15
  • @Fabian I've updated the answer to use `version_compare`. – Nick Aug 24 '20 at 04:19
  • @Fabian sorry about forgetting that function before; I've never actually used it in the real world. But why did you unaccept the answer? – Nick Aug 24 '20 at 04:32
  • @Fabian sorry - I'm not a SOAP expert, so I can't help you with that. – Nick Aug 31 '20 at 21:54