FreakSoft FreakSoft - 5 months ago 66x
PHP Question

Preserve the initial order of array in Symfony2 Doctrine findBy()

I have an array (

) of IDs with the following values:

I'm trying to get some data from the database from entity:

$news=$this->getDoctrine()->getRepository('Bundle:News')->findBy(array('id' => $newsList));

array represents real IDs from the News entity.

But when I do:

foreach($news as $n){

IDs are in order:

How can I preserve the order from beginning in foreach?


As you are doing a global query, you can just order your results by a given property, and a given sort order, so as pointed by the previous answer, you can't.

To have your results ordered exactly as the array you given, you can do this:

$newsList = [3, 1, 4, 2];
$newsRepo = $this->getDoctrine()->getRepository('Bundle:News');

foreach ($newsList as $id) {
    $new = $newsRepo->findOneBy['id' => $id];

    if ($new !== null) {
        $news[] = $new;

Like this, your results are ordered exactly like $newsList, e.g:

foreach ($news as $n) {
    print $n->getId();

// Output: 3 1 4 2