简体   繁体   中英

How to get the data from a collection array in Laravel

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?

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.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM