Search code examples
phpsymfonydoctrinedql

Grouping array values before entering into database


I have a symfony app using doctrine2 and I have this array:

Array ( 
[0] => Array ( [id] => 7 [createdOn] => DateTime Object ( [date] => 2011-03-01))                                        
[1] => Array ( [id] => 9 [createdOn] => DateTime Object ( [date] => 2011-03-12))
)

amd I need the [id] values to be entered into the database grouped by month like this:

| createdOn | id    |
| 2011-03   | {7, 9}|

How can I achieve this?


Solution

  • To create an array with the required format;

    foreach($array as $index => $subArray){
      $yearMonth = subStr($subArray["date"], 0, 7);
      $newData[$yearMonth][] = $subArray["id"];
    }
    
    foreach($newData as $yearMonth => $subArray){
      $newData[$yearMonth] = "{".implode(",", $newData[$yearMonth])."}";
    }
    
    var_dump($newData);