【问题标题】:Laravel group by change keysLaravel 通过更改键分组
【发布时间】:2020-05-22 12:27:23
【问题描述】:

您好,我有预订和开始时间。现在我需要报告它。

        $monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y-m');
        })
        ->map(function ($month) {
            return $this->sumTime($month);
        });

sumTime 是我计算开始时间和结束时间之间差异的函数。 cdate 是助手 -> carbon::parse($date)..

这个结果是:

array:2 [▼
  "2020-01" => 60
  "2020-02" => 420
]

需要

但是对于 API,最好是这样:

[
    "2020" => [
        '01' => 60,
        '02' => 30
    ],
    "2021" => [
        '01' => 30,
    ]
]

我的尝试

很遗憾,我无法做到这一点。我试过了:

    $monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y-m');
        })
        ->map(function ($month) {
            return $this->sumTime($month);
        })
        ->mapToGroups(function ($item,$key) {
            $arrkey = explode('-',$key);
            return [$arrkey[0]=>[$arrkey[1]=>$item]];
        });

但它使这个:

array:1 [▼
  2020 => array:2 [▼
    0 => array:1 [▼
      "01" => 60
    ]
    1 => array:1 [▼
      "02" => 420
    ]
  ]
]

所以我不能做 $res['2020']['01']。怎么办?

【问题讨论】:

  • 使用return [$arrkey[1]=>$item];
  • @AnantSingh---AlivetoDie nope 然后我有array:2 [▼ "01" => array:1 [▼ 0 => 60 ] "02" => array:1 [▼ 0 => 420 ] ]

标签: php laravel eloquent


【解决方案1】:

试试这个:

$monthlyAmounts = Reservation::all()
        ->groupBy(function ($proj) {
            return cdate($proj->start_time)->format('Y');
        })
        ->map(function ($items) {
            return $items->groupBy(function($item) {
                return cdate($item->start_time)->format('m');
            })
            ->map(function($month) {
                return $this->sumTime($month);
            }); 
        });

【讨论】:

  • $items->groupBy(function($item) { return cdate($proj->start_time)->format('m'); }) 将 $proj 更改为 $item,并且 Collection { #532 ▼ #items: array:1 [▼ 2020 => null ] } 你错过了地图中的回报!现在可以了:)谢谢
【解决方案2】:

使用foreach循环的另一种方法

...
$monthlyAmounts = Reservation::all();
$new = [];
foreach($monthlyAmounts as $key => $val)
{
  $dis = explode('-', $key);
  $new[$dis[0]][$dis[1] = $val;
}
print_r($new);

【讨论】:

  • 是的,但我想要更多“类似 laravel”的解决方案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 2018-01-23
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多