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?

有帮助吗?

解决方案

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)

其他提示

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top