Natural sort an associative array?

后端 未结 3 1083
失恋的感觉
失恋的感觉 2020-12-18 06:18

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         


        
相关标签:
3条回答
  • 2020-12-18 06:30

    PHP's usort() allows you to define a custom callback function for sorting:

    usort($array, function($a, $b){
        if ($a['manager'] == $b['manager']) {
            return 0;
        }
        return ($a['manager'] < $b['manager']) ? -1 : 1;
    });
    

    For sorting months, you can use something like date('m', strtotime($a['month'])) to get the month number for comparison. More ways to do that can be found here: convert month from name to number

    0 讨论(0)
  • 2020-12-18 06:36

    You'll can use usort() and write your own comparison function. I started with your example array, then changed the indices to strings just to make sure it worked. I've tested it three ways, and all of them worked, including the array_multisort(if you don't care about keys as you said).

    # Quick, dirty, and probably not suitable for any use, anywhere, by anyone
    $test1 = array();
    $test1["zero"]="June";
    $test1["one"] ="January";
    
    function nat_cmp($a,$b){
            return strnatcmp($a,$b);
    }
    
    #usort($test1, 'nat_cmp'); # Returns {0=>"January",1=>"June"}
    #usort($test1, function($a,$b){return strnatcmp($a,$b);}); # Same
    array_multisort($test1, SORT_ASC, SORT_NATURAL); #Same
    
    var_dump($test1);
    

    (NB: If you do end up needing the keys, you'll definitely have to go the custom rolled path with array_keys or uksort())

    0 讨论(0)
  • 2020-12-18 06:44

    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
    });
    
    0 讨论(0)
提交回复
热议问题