Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在数组对象laravel中计算一些值_Php_Laravel - Fatal编程技术网

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')