Reputation: 87
I have this Collection Array in Laravel
that is from the database
public function getdiagnosistally(){
$jsonData = ListBuilder::all()->pluck('listdata');
$res = $jsonData->contains('Test');
dd($jsonData,$res);
}
I was wondering if it is possible to count the occurrences of the following data inside the collection.
I have tried using below contain method but it does not give me a true result even if there is Test inside the Collection.
$res = $jsonData->contains('Test');
I have also tried using count method but it only gives me the total amount of the collection not the count of Test which is 2 but the result gives me 6.
$res = $jsonData->count('Test');
The end result i was aiming is like it will be counting the occurrences of Test from the json data.
for example :-
Test = 2
Test child 1 = 4
Would you be able to advice how i can fix it?
Upvotes: 2
Views: 1924
Reputation: 188
For instance your database table name is "Checklist" and "test" is a column.
$count = Checklist::Select('checklist.test')->count();
You can also use where if that's the condition ->where('checklist_id', $request->id)
Upvotes: 0
Reputation: 163748
You count the occurrences manually by iterating over collection and JSON data converted to an array.
I've just tested this and it will work for the data format you're using:
$count = 0;
$jsonData->map(function($i) use(&$count) {
$i = json_decode($i, true);
array_map(function($i) use(&$count) {
if (str_contains($i, 'Test')) $count++;
}, $i['checklist']);
});
Upvotes: 0
Reputation: 2711
Since you have a Collection, you could solve it functionally using filter and array_count_values.
array_count_values
to get the desired result.code:
$testValues = $jsonData->flatMap(function($json) {
$data = collect(json_decode($json, true)['checklist']);
return $data->filter(function($item) {
return str_contains($item, 'Test');
});
});
$result = array_count_values($testValues->all());
dd($result);
Note that in this solution I assumed the first level of the json is always "checklist". If not, you have to loop over it.
Upvotes: 1