Php 在数组对象laravel中计算一些值
我有这样的数组Php 在数组对象laravel中计算一些值,php,laravel,Php,Laravel,我有这样的数组 0 => {#682 ▼ +"id": "121" +"total": 0 } 1 => {#659 ▼ +"id": "122" +"total": 1 } 2 => {#672 ▼ +"id": "122" +"total": 1 } 3 => {#677 ▼ +"id": "123" +"total": 1 如果给定一个特定的id,我如何获得总数的总和 e、 g.id=122的总计为2您可以使用col
0 => {#682 ▼
+"id": "121"
+"total": 0
}
1 => {#659 ▼
+"id": "122"
+"total": 1
}
2 => {#672 ▼
+"id": "122"
+"total": 1
}
3 => {#677 ▼
+"id": "123"
+"total": 1
如果给定一个特定的id,我如何获得总数的总和
e、 g.id=122的总计为2您可以使用collect助手及其方法
$id = 122;
// count using filter
$count = collect($myArrayOfObjects)->filter(function ($object) use ($id) { return $object->id === $id; })->count();
// count using where
$count = collect($myArrayOfObjects)->where('id', $id)->count();
// to get the summation of total
$sum = collect($myArrayOfObjects)->where('id', $id)->sum('total');
您的数据看起来像一个集合,因此只需使用sum: 如果它不是集合,只需将其转换为包含collect$data的集合:
$collection->where('id', 122)->sum('total')
collect($data)->where('id', 122)->sum('total')