Reputation: 33674
I have the following code, which tries to sort an array of Products by it's creation date:
private function sortProductsByDate(Product $a, Product $b)
{
if ($a->getCreated() == $b->getCreated()) {
return 0;
}
return ($a->getCreated() < $b->getCreated()) ? -1 : 1;
}
/**
* Get the most 4 recent items
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getMostRecentItems()
{
$userMostRecentItems = array();
$products = $this->getProducts();
usort($products, "sortProductsByDate");
foreach ($this->getProducts() as $product) {
ladybug_dump($product->getCreated());
}
$mostRecentItems = $this->products;
return $this->isLocked;
}
Why does this gives me this error:
Warning: usort() expects parameter 1 to be array, object given
Ideas?
Upvotes: 0
Views: 8404
Reputation: 164910
I'm guessing getProducts()
returns a \Doctrine\Common\Collections\Collection
(most probably an ArrayCollection
). Use
$products = $this->getProducts()->getValues();
You'll also want to use
usort($products, array($this, 'sortProductsByDate'));
and finally, use the $products
array in your foreach
foreach ($products as $product)
Upvotes: 3
Reputation: 11181
I believe the error is clear. It said that the first parameter should be array, but you pass object instead which means that $this->getProducts();
returns objects instead of array.
Try this to see what is the type of variable products. I doubt you are returning a database resource instead of array here.
var_dump($products);
Upvotes: 0