我有以下代码,它尝试按创建日期对产品数组进行排序:
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;
}
为什么这会给我这个错误:
Warning: usort() expects parameter 1 to be array, object given
想法?
我猜getProducts()
返回一个'Doctrine'Common'Collections'Collection
(很可能是一个ArrayCollection
)。用
$products = $this->getProducts()->getValues();
您还需要使用
usort($products, array($this, 'sortProductsByDate'));
最后,在foreach
中使用$products
数组
foreach ($products as $product)
我相信
错误很明显。它说第一个参数应该是数组,但你传递对象,这意味着$this->getProducts();
返回对象而不是数组。
试试这个,看看可变产品的类型是什么。我怀疑您在这里返回的是数据库资源而不是数组。
var_dump($products);