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

报告相同问题?