Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
605 views
in Technique[技术] by (71.8m points)

php - Natural sort an associative array?

Given an array of arrays, how would I natural sort the inner arrays based on their values?

Example array:

array (size=2)
  0 => 
    array (size=1)
      'manager' => string 'Manager 1' (length=9)
  1 => 
    array (size=1)
      'manager' => string 'Manager 3' (length=9)

Another example array:

array (size=2)
  0 => 
    array (size=1)
      'month' => string 'June' (length=4)
  1 => 
    array (size=1)
      'month' => string 'January' (length=7)

My first idea was to just natsort() them, but that expects a normal array. The next idea was to use array_multisort($array, SORT_NATURAL);, but that didn't work due to the associative arrays.

So, how could I sort the inner arrays in using natural sorting? Also, keeping array keys doesn't matter in this case.

EDIT:

Expected output of array 1 would be the same (since Manager 1 and Manager 3 are already in order):

array (size=2)
  0 => 
    array (size=1)
      'manager' => string 'Manager 1' (length=9)
  1 => 
    array (size=1)
      'manager' => string 'Manager 3' (length=9)

Expected output of array two would put January ahead of June (the 'natural' order):

// 0 and 1 keys can switch or stay the same, doesn't matter
array (size=2)
  0 => 
    array (size=1)
      'month' => string 'January' (length=4)
  1 => 
    array (size=1)
      'month' => string 'June' (length=7)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well!, You can simplify the function using natural sort functions like this:

usort($array, function($a, $b){
    return strnatcmp($a['manager'],$b['manager']); //Case sensitive
    //return strnatcasecmp($a['manager'],$b['manager']); //Case insensitive
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...