简体   繁体   中英

How can I sort a multidimensional array naturally?

I have an array like this:

[
    ['number' => '419-1'],
    ['number' => '302-1'],
    ['number' => '102-1'],
    ['number' => '102-11'],
    ['number' => '203-1'],
    ['number' => '508-1'],
    ['number' => '105-1'],
    ['number' => '102-2'],
    ['number' => '302-2'],
]

I want output like this:

[
    ['number' => '102-1'],
    ['number' => '102-2'],
    ['number' => '102-11'],
    ['number' => '105-1'],
    ['number' => '203-1'],
    ['number' => '302-1'],
    ['number' => '302-2'],
    ['number' => '419-1'],
    ['number' => '508-1']
]

Problem is number is stored as string. I want to treat number as integer. Sorting needs to be done numerically. Not string comparison. I tried with usort but that did not help.

Can someone please help me?

$arr =    [
        ['number' => '419-1'],
        ['number' => '419-11'],
        ['number' => '102-1'],
        ['number' => '203-1'],
        ['number' => '508-1'],
        ['number' => '105-1'],
        ['number' => '102-2'],
        ['number' => '302-2'],
    ];

    usort($arr, function($a,$b){

        $an = explode('-',$a['number']);
        $bn = explode('-',$b['number']);

        if($an[0] == $bn[0]){
            return $an[1]*1 > $bn[1]*1;
        }

        return $an[0]*1 > $bn[0]*1;

    });

    print_r($arr);

You are wanting to naturally sort the array values, 1, 2, 10, 20 so they are not sorted as a numeric string 1, 10, 2, 20 . The results of which should be the same in PHP 5 and PHP 7.

You can use array_multisort with the SORT_ASC and SORT_NATURAL flags, along with array_column to retrieve the values to sort by.

Example https://3v4l.org/BNCe5

PHP 5.5+

array_multisort(array_column($ar, 'number'), SORT_ASC, SORT_NATURAL, $ar);
var_export($ar);

Alternatively you can use strnatcmp with usort .

PHP 5.3+

usort($ar, function($a, $b) {
   return strnatcmp($a['number'], $b['number']);
});
var_export($ar);

Result

array (
  0 => 
  array (
    'number' => '102-1',
  ),
  1 => 
  array (
    'number' => '102-2',
  ),
  2 => 
  array (
    'number' => '102-11',
  ),
  3 => 
  array (
    'number' => '105-1',
  ),
  4 => 
  array (
    'number' => '203-1',
  ),
  5 => 
  array (
    'number' => '302-1',
  ),
  6 => 
  array (
    'number' => '302-2',
  ),
  7 => 
  array (
    'number' => '419-1',
  ),
  8 => 
  array (
    'number' => '508-1',
  ),
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM