开发者

Array sort function in PHP

I defined a myArr = ("Apr","Mar","May"). Is there a sorting function to sort the开发者_运维问答 array members by nature month sequence otherwise by alphabet.

The array members variables can will be changed at runtime.

I want it output followed Mar, Apr, May using foreach loop.


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;
}


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", "ddd", "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] => ddd
    [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 "ddd", "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] => ddd
)

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜