vpetkovic
2/9/2019 - 5:11 PM

Group SQL results by column

$data = [
  {
  "id": "custom",
  "text": "Custom",
  "Category": "Events",
  "ddl_name": "options"
  },
  {
  "id": "dayoff",
  "text": "Day Off",
  "Category": "Events",
  "ddl_name": "options"
  }
]

$byGroup = group_by("Category", $ddl_list);

//Output 
"Events": [
  {
  "id": "custom",
  "text": "Custom",
  "Category": "Events",
  "ddl_name": "options"
  },
  {
  "id": "dayoff",
  "text": "Day Off",
  "Category": "Events",
  "ddl_name": "options"
  }
]

// Group by function
  function group_by($key, $data) {
        $result = array();
        
        foreach($data as $val) {
            if(array_key_exists($key, $val)){
                $result[$val[$key]][] = $val;
            }else{
                $result[""][] = $val;
            }
        }
        
        return $result;
    }