1

I have a simply query like this:

$events = EventHistory::where('u_h_id', $id)
                      ->where('has_read', 0)
                      ->get(['event_type']);

This will return a result that looks like this:

[
{
event_type: 1
},
{
event_type: 2
},
{
event_type: 2
},
{
event_type: 4
},
{
event_type: 6
},
{
event_type: 1
},
{
event_type: 3
},
{
event_type: 1
},
{
event_type: 4
},
{
event_type: 1
},
{
event_type: 4
},
{
event_type: 4
}]

But now I need a way to count the specific values so I can return now many results exist in the different event types

eg, on the result above I want to return

$type1 = 4;
$type2 = 2;
$type3 = 1;
$type4 = 4;
$type6 = 1;

There are 4 results that has a event_type value of 1 etc..

1
  • Do you want RDBMS server do it for you or you want to do it in PHP script (via collections). Also share table schema. Commented Aug 2, 2017 at 17:43

2 Answers 2

2

Dummy way to do it is use foreach

$result = [];
foreach($events as $key => $value) {
    $result[$value['event_type']] = isset($result[$value['event_type']]) ? $result[$value['event_type']]+1 : 1;
}

// now you have indexed array $result with the desired output

http://sandbox.onlinephpfunctions.com/code/b49150f192b99b218708d5dd8037fe5a23457a79

Sign up to request clarification or add additional context in comments.

Comments

1

Got it to work using this:

$events = EventHistory::where('u_h_id', $id)
    ->where('has_read', 0)
    ->select('event_type', \DB::raw('count(*) as count'))
    ->groupBy('event_type')
    ->get();

1 Comment

Well of course, I linked you to the duplicate, I hope this gets closed, next time do search before asking.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.