Metono
Metono

Reputation: 87

How to get the data from a collection array in Laravel

I have this Collection Array in Laravel that is from the database enter image description here

 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');

enter image description here

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

Answers (3)

Shariq Shaikh
Shariq Shaikh

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

Alexey Mezenin
Alexey Mezenin

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

winkbrace
winkbrace

Reputation: 2711

Since you have a Collection, you could solve it functionally using filter and array_count_values.

  1. First we decode the json to array and wrap it in a Collection.
  2. Then we filter to keep only the values containing the string 'Test'
  3. We use flatMap to get all these values in a single array
  4. So we can finally use 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

Related Questions