代码之家  ›  专栏  ›  技术社区  ›  b00sted 'snail'

使用laravel集合对月份数组进行排序

  •  2
  • b00sted 'snail'  · 技术社区  · 6 年前

    我的阵法是

    $array = [
     1 => 0
     2 => 0
     3 => 0
     4 => 0
     5 => 0
     6 => 0
     7 => 2
     8 => 0
     9 => 0
     10 => 1
     11 => 0
     12 => 1
    ];
    

    $array = [
     10 => 1
     11 => 0
     12 => 1
     1 => 0
     2 => 0
     3 => 0
     4 => 0
     5 => 0
     6 => 0
     7 => 2
     8 => 0
     9 => 0
    ];
    

    $sorted = collect($array)
      ->sortBy(function ($count, $month) {
        return $month <= 9;
      });
    

    但结果并不是我所期望的:(

    请帮帮我!

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jonathon    6 年前

    你可以这样做:

    $sorted = collect($array)->sortBy(function ($count, $month) {
        $currentMonth = (int) \Carbon\Carbon::now()->month;
    
        return ($month + (12 - $currentMonth - 1)) % 12;
    });
    
        2
  •  -1
  •   Hartanto Ignatius    6 年前

    你可以用php函数

    krsort();

    ksort($array);