Array sort function in PHP

前端 未结 3 990
一向
一向 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 "
    ";
    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.

提交回复
热议问题