【问题标题】:usort parameter issueusort参数问题
【发布时间】:2013-09-13 14:07:26
【问题描述】:

我有以下代码,它尝试按产品的创建日期对数组进行排序:

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 

想法?

【问题讨论】:

标签: php usort


【解决方案1】:

我猜getProducts() 返回一个\Doctrine\Common\Collections\Collection(很可能是一个ArrayCollection)。使用

$products = $this->getProducts()->getValues();

你也会想要使用

usort($products, array($this, 'sortProductsByDate'));

最后,在foreach 中使用$products 数组

foreach ($products as $product)

【讨论】:

    【解决方案2】:

    我相信错误很明显。它说第一个参数应该是数组,但是你传递对象而不是这意味着$this-&gt;getProducts();返回对象而不是数组。

    试试这个看看可变产品的类型是什么。我怀疑您在这里返回的是数据库资源而不是数组。

    var_dump($products);

    【讨论】:

      猜你喜欢
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      相关资源
      最近更新 更多