FreakSoft FreakSoft - 7 months ago 83
PHP Question

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

I have an array (

$newsList
) of IDs with the following values:
4,2,1,3
.

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

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


$newsList
array represents real IDs from the News entity.

But when I do:

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


IDs are in order:
1,2,3,4
.

How can I preserve the order from beginning in foreach?

Answer

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