Skip to content
Advertisement

Laravel : convert grouped data to one row

Hello please i want to convert grouped data with duplicated keys and different values to one row. For example :

    "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",
    }
    ....
 } 
    ...

what i want to do is convert all this arrays with common key to one array or one row in the database where data are grouped like the example the data are grouped by group field and what i want to do is like that :

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

Please could you help to fix by php code (laravel model) or SQL query and thank you so much !

Advertisement

Answer

try this

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

    }

EDITED

you have use " " fo null so use like below

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

        }

EDITED 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);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement