duan4369 2015-01-04 19:27
浏览 91
已采纳

从Doctrine2获取值数组的正确方法

I'm currently coding a newsletter system. In order to send the mail, I need to get all e-mail addresses from my database (of course).

So I created a custom repository method, as follows :

public function getEmailAddresses()
{
    $query = $this->getEntityManager()->createQueryBuilder()
        ->select('u.email')
        ->from('AppBundle:User', 'u')
        ->where('u.isNewsletterSubscriber = true')
    ;

    $results =  $query->getQuery()->getResult();

    $addresses = [];
    foreach($results as $line) {
        $addresses[] = $line['email'];
    }

    return $addresses;
}

I am wondering if there is a better way to do so than treating the result to get a "plain" array containing only e-mail addresses. In effect, after $query->getQuery()->getResult(), I get something like this :

'results' =>
 [0] => array('email' => 'first@email.com')
 [1] => array('email' => 'second@email.com')

And as I said, I want something like this :

array('first@email.com', 'second@email.com')

Does a cleaner way to do that exist using Doctrine2 built-in methods ? I've tried with different hydratation modes but nothing worked.

Thanks in advance :)

  • 写回答

4条回答 默认 最新

  • dongyuli4538 2015-01-04 19:52
    关注

    You could probably create a custom hydrator, but there's really no issue with just doing it the way you are right now. You could also do it in the following ways:

    PHP <= 5.4

    return array_map('current', $addresses);
    

    PHP >= 5.5

    return array_column('email', $addresses);
    

    The array_column function was introduced in PHP 5.5.0 and does what you're looking for. The array_map function will work otherwise, calling PHP's internal current function which simply returns the value of the current element (which is always initialized to the first element of that array).

    Be careful with using array_map if you have a large number of rows returned, because it will likely be slower and it will definitely take up a lot more memory since it has to copy the array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题