组数组的数组php

I have a query that produces this kind of result when converting to JSON. The result is from this query:

$query = "SELECT template_groups.id,template_groups.template_id , templates.color_ref
          FROM `template_groups`,`templates`
          where templates.template_id = template_groups.template_id  ";

Result:

array(135) {
  [0]=>
  array(2) {
    ["template_groups"]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["template_id"]=>
      string(1) "1"
    }
    ["templates"]=>
    array(1) {
      ["color_ref"]=>
      string(6) "F1F1F1"
    }
  }
  [1]=>
  array(2) {
    ["template_groups"]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["template_id"]=>
      string(1) "2"
    }
    ["templates"]=>
    array(1) {
      ["color_ref"]=>
      string(6) "00326E"
    }
  }
  [2]=>
  array(2) {
    ["template_groups"]=>
    array(2) {
      ["id"]=>
      string(1) "1"
      ["template_id"]=>
      string(1) "3"
    }
    ["templates"]=>
    array(1) {
      ["color_ref"]=>
      string(6) "191919"
    }
  }
}

I would like to group the result so that for each template_groups, I have inside it all the templates. What could be the best solution in PHP? The wanted result is an array of template_groups, each one has the corresponding array of template_id and its color.