Reputation: 7128
How can I sum sessions
value of this array?
Collection {#3646 ▼
#items: array:2 [▼
0 => array:2 [▼
"type" => "New Visitor"
"sessions" => 154
]
1 => array:2 [▼
"type" => "Returning Visitor"
"sessions" => 59
]
]
}
$analyticsData4 = Analytics::fetchUserTypes(Period::months(1));
this code return my dd above. I need to sum sessions value of New Visitors and Returning Visitors
Upvotes: 0
Views: 456
Reputation: 4634
There is a helper for that, you just use sum
like the following.
$analyticsData4->sum('sessions');
You can read more about Laravel Collection here.
Upvotes: 0
Reputation: 783
Just convert your collection to Json like following,
$json = $analyticsData4->toJson();
Then, use this package jsonq to sum/count/size/traverse/find whatever you want quite easily.
For example,
$q = new Jsonq('data.json');
$res = $q->from('products')
->where('cat', '=', 1)
->sum('price');
Note, this might look a lots work for this simple problem but certainly it will help you across the project.
Upvotes: 5
Reputation: 7128
$totalUsers = $analyticsData4->sum(function ($analyticsData4) {
return $analyticsData4['sessions'];
});
Upvotes: 2