在进入数据库之前对数组值进行分组

时间:2013-03-08 08:01:39

标签: php symfony doctrine dql

我有一个使用doctrine2的symfony应用程序,我有这个数组:

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

amd我需要将[id]值输入到按月分组的数据库中,如下所示:

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

我怎样才能做到这一点?

4 个答案:

答案 0 :(得分:1)

创建具有所需格式的数组;

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);

答案 1 :(得分:0)

这是您的学说查询构建器的一部分:

$date = explode('-', $array[0]['date']);
$fromDate = new \DateTime($date[0].'-'.$date[1].'-'01 00:00:00); // 2011-03-01 00:00:00
$toDate = $fromDate;
$toDate->modify('+1 month'); // 2011-04-01 00:00:00

$qb = $this->createQueryBuilder('a')
     ->select('a.id')
     ->where('a.createdOn >= :fromDate')
     ->andWhere('a.createdOn < :toDate') // strictly inferior
     ->setParameter('fromDate', $fromDate->format('Y-m-d H:i:s'))
     ->setParameter('toDate', $toDate->format('Y-m-d H:i:s'));

使用此查询,您搜索创建日期介于“2011-03-01 00:00:00”(包含)和“2011-04-01 00:00:00”(排除)之间的实体的ID,所以在3月份创造了一个!

答案 2 :(得分:0)

试试这个:

$res           = array();
foreach($your_array as $val){
    $dt        = new DateTime($val['createdOn']->date); 
    $res[$dt->format('Y-m')][] = $val['id'];
}

foreach($res as &$val){
   $val        = json_encode($val);
}

echo "<pre>";
print_r($res);

答案 3 :(得分:0)

按照描述创建一个doctrine事件监听器 http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html并将ID添加到另一个数据库。