如何从Laravel中的集合数组中获取数据

时间:2018-01-10 14:35:47

标签: php laravel

我在index中有一个来自数据库的Collection数组 enter image description here

Laravel

我想知道是否可以计算集合中以下数据的出现次数。

我尝试使用下面的contains方法,但即使在Collection中有Test,它也不会给我一个真实的结果。

 public function getdiagnosistally(){

      $jsonData = ListBuilder::all()->pluck('listdata');
        $res = $jsonData->contains('Test');
        dd($jsonData,$res);
}

我也尝试过使用count方法,但它只给我收集的总量而不是Test的计数为2,但结果给了我6。

 $res = $jsonData->contains('Test');

enter image description here

我瞄准的最终结果就像从json数据计算Test的出现次数。

例如: -

 $res = $jsonData->count('Test');

你能告诉我如何解决它吗?

2 个答案:

答案 0 :(得分:1)

由于您有一个集合,您可以使用filterarray_count_values在功能上解决它。

  1. 首先,我们将json解码为数组并将其包装在Collection中。
  2. 然后我们过滤以仅保留包含字符串'测试'
  3. 的值
  4. 我们使用flatMap在单个数组中获取所有这些值
  5. 因此,我们最终可以使用array_count_values来获得所需的结果。
  6. 代码:

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

    请注意,在此解决方案中,我假设json的第一级始终是" checklist"。如果没有,你必须循环它。

答案 1 :(得分:0)

通过迭代收集和转换为数组的JSON数据来手动计算出现次数。

我刚刚对此进行了测试,它将适用于您正在使用的数据格式:

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