Laravel 按项目键的集合总和
Laravel Collection Sum by Item Key
我有以下 Laravel 集合 $output。我想对性别 1 和 2 的每个值求和。我试过 $output->sum('total') 但它给出了总计。
Illuminate\Support\Collection {#1334 ▼
#items: array:11 [▼
0 => {#1348 ▼
+"total": 1037931027.8459
+"status": 2
+"sex": 1
}
1 => {#1346 ▼
+"total": 1091237622.0488
+"status": 2
+"sex": 2
}
2 => {#1342 ▼
+"total": 1103340160.4262
+"status": 1
+"sex": 1
}
3 => {#1349 ▼
+"total": 6004661.498201
+"status": 4
+"sex": 1
}
]
}
查看 documentation 您可以筛选集合然后求和。像这样:
$output->whereIn('sex', [1,2])->sum('total')
我有以下 Laravel 集合 $output。我想对性别 1 和 2 的每个值求和。我试过 $output->sum('total') 但它给出了总计。
Illuminate\Support\Collection {#1334 ▼
#items: array:11 [▼
0 => {#1348 ▼
+"total": 1037931027.8459
+"status": 2
+"sex": 1
}
1 => {#1346 ▼
+"total": 1091237622.0488
+"status": 2
+"sex": 2
}
2 => {#1342 ▼
+"total": 1103340160.4262
+"status": 1
+"sex": 1
}
3 => {#1349 ▼
+"total": 6004661.498201
+"status": 4
+"sex": 1
}
]
}
查看 documentation 您可以筛选集合然后求和。像这样:
$output->whereIn('sex', [1,2])->sum('total')