0

我有一个数组,但我需要按顺序对其进行排序。有什么简单的方法可以做到这一点?数组如下所示:

( [01/2012] => 0 [01/2013] => 4 [02/2011] => 0 [02/2012] => 0
[03/2011] => 0 [03/2012] => 0 [04/2011] => 0 [04/2012] => 0
[05/2011] => 0 [05/2012] => 0 [06/2011] => 0 [06/2012] => 0
[07/2011] => 0 [07/2012] => 0 [08/2011] => 0 [08/2012] => 1
[09/2011] => 0 [09/2012] => 5 [10/2011] => 0 [10/2012] => 3
[11/2011] => 0 [11/2012] => 7 [12/2011] => 0 [12/2012] => 2 ) 

我需要它从最远回到最新。

4

2 回答 2

2

您将使用uksort功能。

uksort ( $myArray , function($keyA, $keyB){
    $monthYearA = explode('/', $keyA);
    $monthYearB = explode('/', $keyB);
    return $monthYearA[1].$monthYearA[0] >
           $monthYearB[1].$monthYearB[0] ? 1 : -1;
});
于 2013-02-07T22:00:20.100 回答
-1

通过将每个键转换为 unix 时间戳,对键进行排序(ksort),然后再次将它们变成月份和年份来解决它。

      while($row = mysql_fetch_array($conversions_query)){
    if($row['data']){
      $data = unserialize($row['data']);
      foreach($data as $month=>$visits){
        if($visits == ""){
          $visits = 0;
        }
        $monthstring = explode("/", $month);
        $output[strtotime($monthstring[0]."/01/".$monthstring[1])] = $visits;
      }
    }
  }

  ksort($output);

  foreach($output as $key => $val){
    $thisdate = date("m/y", $key)."<br>";
    $output[$thisdate] = $output[$key];
    unset($output[$key]);
  }

  echo "<br>SORTED OUTPUT: ";
  print_r($output);
于 2013-02-07T22:36:28.773 回答