-1

I'm trying to achieve the following:

Lets say I have a collection 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 which id is on the array, I hope you can understand me.

What I tried with no success (can't 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
]
0

1 Answer 1

0

I'm not sure you should do that with sortBy function cause you sorting by the ID's array so you should iterate over it and not the collection.
This can be handled with PHP std only:

$products = [[ "id"=> 1, "name"=> "example1", "price"=> 10 ], [ "id"=> 2, "name"=> "example2", "price"=> 20 ],  [ "id"=> 3, "name"=> "example3", "price"=> 30 ]];
$sortByArr = [3, 2];

$sortedArray = array_reduce($sortByArr, function($array, $index) use (&$products) {
    $productIndex = array_search($index, array_column($products, "id"));
    $array[] = $products[$productIndex];
    unset($products[$productIndex]);
    return $array;
}, []);

var_dump(array_merge($sortedArray, $products));
Sign up to request clarification or add additional context in comments.

2 Comments

It doesnt work, it results in a single item array and i dont want that, i want the same collection but reordered by the array of the ids.
I didn't write it because you can do it in several ways, and you need to choose the one who will cost you at least. I edited my answer to present one way to do this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.