0

I am struggling with alphanumeric array sorting, I have below array and I the result identical to the result of JavaScript sorting function localecompare() below is my code:

<?php
    $arr = array(
        array( 'label' => '#C' ),
        array( 'label' => '!A' ),
        array( 'label' => '@B' ),
        array( 'label' => 'g' ),
        array( 'label' => '98' ),
        array( 'label' => 'G' )
    );

    usort($arr, function($a, $b) {
    return strnatcasecmp($a['label'], $b['label']);
    });

    print_r($arr);

Output:

Array (
    [0] => Array ( [label] => !A )
    [1] => Array ( [label] => #C )
    [2] => Array ( [label] => 98 )
    [3] => Array ( [label] => @B )
    [4] => Array ( [label] => g )
    [5] => Array ( [label] => G )
)

But I am trying to achieve the result as below which is equivalent to the result of JavaScript sorting function localecompare()

Expected:

Array
(
    [0] => Array ( [label] => !A )    
    [1] => Array ( [label] => @B )    
    [2] => Array ( [label] => #C )
    [3] => Array ( [label] => 98 )    
    [4] => Array ( [label] => g )    
    [5] => Array ( [label] => G )    
)
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
lazyCoder
  • 2,544
  • 3
  • 22
  • 41
  • Great thanks to you but yes went through that question which is not solved and marked also not working in my case thanks again – lazyCoder Oct 10 '19 at 12:49
  • There are more in the link above. Let me know if you could not solve it and why, then I can re-open – mplungjan Oct 10 '19 at 13:09

0 Answers0