mafortis
mafortis

Reputation: 7128

sum collection in laravel

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
    ]
  ]
}

Code

$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

Answers (3)

Set Kyar Wa Lar
Set Kyar Wa Lar

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

Abdur Rahman
Abdur Rahman

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

mafortis
mafortis

Reputation: 7128

Solved

$totalUsers = $analyticsData4->sum(function ($analyticsData4) {
  return $analyticsData4['sessions'];
});

Upvotes: 2

Related Questions