Reputation:
I want to count the number of times a specific value occurs in an array in Laravel PHP
I have tried it like this
$posts = RedditPosts::where('search_identifier', $search_id)->get();
$sentimentPost = array_count_values($posts->sentiment);
dd($sentimentPost);
and I get this error
Undefined property: Illuminate\Database\Eloquent\Collection::$sentiment
I have a field in my table called 'sentiment' and it is either positive, neutral or negative.
What I want to do is find out if the overall sentiment for each of the objects is positive, neutral or negative and parse that variable to a view where it can be displayed.
So basically I want to count how many times the positve, negative and neutral comes up from the results so I can compare them to one another and find out if the overall sentiment is positve, negative or neutral. In the DB i have many columns, i.e post, sentiment etc.
array_count_values is the closest thing I have found to be able to do this. Is there another way?
Upvotes: 4
Views: 3536
Reputation: 219938
Simply call the collection's count
method:
$count = $posts->count();
If all you need is the count, you can do it directly in the database:
$count = RedditPosts::where('search_identifier', $search_id)->count();
If you want the count per sentiment, you can group by sentiment, then map the values to their count:
$counts = $posts->groupBy('sentiment')->map->count();
...which will give you the count for each sentiment:
dd($counts->all()); // ['positive' => 4, 'negative' => 2, 'neutral' => 9]
Alternatively, you can do all of the grouping and counting directly in the database:
RedditPosts::where('search_identifier', $search_id)
->selectRaw('sentiment, COUNT(*) as count')
->groupBy('sentiment')
->pluck('count', 'sentiment');
...which will return the same associative array as the code above.
Upvotes: 7
Reputation: 7083
If I understood what you want, an approach to this problem would be:
$sentiments = [
'positive' => 0,
'neutral' => 0,
'negative' => 0,
];
foreach ($posts as $post) {
$sentiments[$post->sentiment]++;
}
dd($sentiments);
Hope it helps...
Upvotes: 0