Array sort function in PHP

前端 未结 3 956
一向
一向 2020-12-22 12:04

I defined a myArr = (\"Apr\",\"Mar\",\"May\"). Is there a sorting function to sort the array members by nature month sequence otherwise by alphabet.

Th

相关标签:
3条回答
  • 2020-12-22 12:14

    Bulding on @preinheimer's answer, here is a version that will do a sequential sort if the name doesn't exist:

    $data = array("Apr", "Mar", "Jan", "Feb", "ffffd", "aaa", "ccc");
    
    function monthCompare($a, $b) {
        $a = strtolower($a);
        $b = strtolower($b);
        $months = array(
            'jan' => 1,
            'feb' => 2,
            'mar' => 3,
            'apr' => 4,
            'may' => 5
        );
        if($a == $b)
            return 0;
        if(!isset($months[$a],$months[$b]))
            return $a > $b;
        return ($months[$a] > $months[$b]) ? 1 : -1;
    }
    
    usort($data, "monthCompare");
    
    echo "<pre>";
    print_r($data);
    

    Returns:

    Array
    (
        [0] => aaa
        [1] => ccc
        [2] => ffffd
        [3] => Jan
        [4] => Feb
        [5] => Mar
        [6] => Apr
    )
    

    However - this highlights logic flaw with your question. You've asked that it be sorted by month sequence otherwise by alphabet. The problem with that is you haven't sufficiently defined the sort order in a way that can be reliabliy replicated. For example, using the above algorythm and the array "ffffd", "aaa", "ccc", "Apr", "Mar", "Jan", "Feb" (ie, same elements) gives the result:

    Array
    (
        [0] => aaa
        [1] => Jan
        [2] => Feb
        [3] => Mar
        [4] => Apr
        [5] => ccc
        [6] => ffffd
    )
    

    Both answers are correct according to your request, so you need to define the sort requirement in more detail.

    0 讨论(0)
  • 2020-12-22 12:17

    You could use usort() and create your own function to compare months.

    function monthCompare($a, $b)
    {
      $months = array('jan' => 1, 'feb' => 2..._);
      if($a == $b)
      {
        return 0;
      }
      return ($months[$a] > $months[$b]) ? 1 : -1;
    }
    
    0 讨论(0)
  • 2020-12-22 12:18

    No. there is no such a function. But.... you still can solve your problem gracefully. You should associate months names with numbers (1 is for Jan, 2 is for Feb and so on). This is the most common approach in programming.

    Define your array as:

    $myArr = array(1=>"Jan", 2=>"Feb" ... )
    

    And then you can sort your $myArr by keys (ksort):

    ksort($myArr);
    var_export($myArr);
    

    That would sort your array in ascendant order by keys.

    0 讨论(0)
提交回复
热议问题