我需要一个建议。 我在laravel控制器中得到一个名为$ dettaglioOre的多维数组,我尝试dd($ dettaglioOre),结果如下:
array array:5
0 => array:2 [▼
"categoria" => 1
"ore" => "3.00"
]
1 => array:2 [▼
"categoria" => 2
"ore" => "2.00"
]
2 => array:2 [▼
"categoria" => 3
"ore" => "6.00"
]
3 => array:2 [▼
"categoria" => 1
"ore" => "6.00"
]
4 => array:2 [▼
"categoria" => 2
"ore" => "4.00"
]
]
我该如何按小时数对类别进行分组?
像这样:
类别1 = 9小时
类别2 = 6小时
类别3 = 6小时
非常感谢...
答案 0 :(得分:0)
您可以使用Collections
进行分组:
$items = [
[
"categoria" => 1,
"ore" => "3.00"
],
[
"categoria" => 2,
"ore" => "2.00"
],
[
"categoria" => 3,
"ore" => "6.00"
],
[
"categoria" => 1,
"ore" => "6.00"
],
[
"categoria" => 2,
"ore" => "4.00"
]
];
$result = collect($items)
->groupBy("categoria")
->map(function ($item) {
$item = collect($item);
return [
"categoria" => $item[0]["categoria"],
"ore_sum" => $item->sum("ore")
];
});
dd($result->toArray());
这是结果:
array:3 [▼
1 => array:2 [▼
"categoria" => 1
"ore_sum" => 9.0
]
2 => array:2 [▼
"categoria" => 2
"ore_sum" => 6.0
]
3 => array:2 [▼
"categoria" => 3
"ore_sum" => 6.0
]
]
答案 1 :(得分:0)
您可以尝试-
$newArray = array();
foreach($array as $data) {
if(!array_key_exists($data['categoria'], $newArray))
$newArray[ $data['categoria'] ] = 0;
$newArray[ $data['categoria'] ] += (double)$data['ore'];
}
答案 2 :(得分:0)
$array = [
[
"categoria" => 1,
"ore" => "3.00"
],
[
"categoria" => 2,
"ore" => "2.00"
],
[
"categoria" => 3,
"ore" => "6.00"
],
[
"categoria" => 1,
"ore" => "6.00"
],
[
"categoria" => 2,
"ore" => "4.00"
]
];
foreach($array as $key => $row){
$grouped[$row['categoria']] += $row['ore'];
}
echo '<pre>';
print_r($grouped);
答案 3 :(得分:0)
最后一件事...
如果字段类别属于一种称为categoriaIntervento的关系(一对多),则在视图中检索结果后,如何显示类别名称而不是ID?
我尝试过
foreach($result as $res)
{
{{ $res['ore']->categoriaIntervento->name
}
...但不起作用。
谢谢;)