dimanche 3 décembre 2017

Laravel - Sort collection with a specific order given by an array of ids

Im trying to achieve the following:

Lets say i have a collectiom of products like this one:

$products =

[{ id: 1, name: example1, price: 10 }, {id: 2, name: example2, price: 20}]

And one array with one id:

[0 => 2]

I want to sort the $products collection with the array, that would result in showing the product with the id 2 first inside the collection or in similar words give order priority for the items in the collection wich id is on the array, i hope you can understand me.

What i tried with no sucess (cant see any changes):

$events = $events->sortBy(function($model) use ($ToposDestaques) {
                return array_search($model->getKey(), $ToposDestaques);
            });

$events has two items with id 1 and id 2.

$TopoDestaques has the following value:

array:1 [
  0 => 2
]

Thank you.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire