繁体   English   中英

Laravel:将分组数据转换为一行

[英]Laravel : convert grouped data to one row

您好,我想将具有重复键和不同值的分组数据转换为一行。 例如 :

    "book1" {
    {
        "id" : "1",
        "group" : "book1",
        "name" : "Book X",
        "buy" : "null",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "100",
        "test" : "null",
    } ,
    {
        "id" : "1",
        "group" : "book1",
        "name" : "null",
        "buy" : "null",
        "test" : "344",
    }
 },
    "book2" {
 {
        "id" : "1",
        "group" : "book2",
        "name" : "Book Y",
        "buy" : "null",
        "test" : "null",
    }
    ....
 } 
    ...

我想要做的是将所有这些带有公用键的数组转换为数据库中的一个数组或一行,其中数据像示例一样分组,数据按组字段分组,我想要做的就是这样:

{
  "id" : "1",
  "group" : "book1",
  "name" : "Book X",
  "buy" : "100",
  "test" : "344",
}

请你能帮助修复 php 代码(laravel 模型)或 SQL 查询,非常感谢!

尝试这个

 $data = []; // your data
    $response = [];
    foreach($data as $key => $d){
       if($d['id'] != null) $response[$key]['id'] = $d['id'];
       if($d['group'] != null) $response[$key]['group'] = $d['group'];
       if($d['name'] != null) $response[$key]['name'] = $d['name'];
       if($d['buy'] != null) $response[$key]['buy'] = $d['buy'];
       if($d['test'] != null) $response[$key]['test'] = $d['test'];

    }

已编辑

你已经使用了" " fo null 所以使用如下

$response = [];
        foreach($data as $key => $d){
           if($d['id'] != "null") $response[$d['group']]['id'] = $d['id'];
           if($d['group'] != "null") $response[$d['group']]['group'] = $d['group'];
           if($d['name'] != "null") $response[$d['group']]['name'] = $d['name'];
           if($d['buy'] != "null") $response[$d['group']]['buy'] = $d['buy'];
           if($d['test'] != "null") $response[$d['group']]['test'] = $d['test'];

        }

编辑 2

$response = [];
            foreach($data as $key => $row){
                $array = [];
               foreach($row as $d){
                if($d['id'] != null) $array['id'] = $d['id'];
                if($d['group'] != null) $array['group'] = $d['group'];
                if($d['name'] != null) $array['name'] = $d['name'];
                if($d['buy'] != null) $array['buy'] = $d['buy'];
                if($d['test'] != null) $array['test'] = $d['test'];
               }
              $response[$key][] = $array;
            }

    dd($response);

使用 groupBy()

$data = App\ModelName::groupBy('test')->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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