【问题标题】:Get last element in Collection获取集合中的最后一个元素
【发布时间】:2015-12-07 00:47:11
【问题描述】:

我正在尝试获取集合中最后一个元素的属性。我试过了

end($collection)->getProperty()

$collection->last()->getProperty()

没有任何作用

(告诉我我正在尝试在布尔值上使用 getProperty())。

/**
 * Get legs
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getLegs()
{
    return $this->aLegs;
}

public function getLastlegdate()
{
    $legs = $this->aLegs;

    return $legs->last()->getStartDate();
}

知道为什么吗?

【问题讨论】:

  • 你确定$collection里面有项目吗? end() 将在一个空数组上返回 false
  • 请提供一些代码帮助我们更好的理解帮助您
  • $collection->last();

标签: php symfony collections doctrine doctrine-collection


【解决方案1】:

您遇到的问题是由于集合是空的。 在内部 last() 方法使用 end() php 函数 from the doc:

返回最后一个元素的值,如果是空数组则返回 FALSE。

所以改变你的代码如下:

$property = null

if (!$collection->isEmpty())
{
$property =  $collection->last()->getProperty();
}

希望有帮助

【讨论】:

    【解决方案2】:

    这个$collection->last()->getProperty() 违反了得墨忒耳法则。该功能应该有一个单一的职责。试试这个。

    /**
     * @return Leg|null
     */
    public function getLastLeg(): ?Leg
    {
       $lastLeg = null;
       if (!$this->aLegs->isEmpty()) {
         $lastLeg = $this->aLegs->last();
       }
       return $lastLeg;
    }
    
    /**
     * @return \DateTime|null
     */
     public function getLastLegDate(): ?\DateTime
     {
       $lastLegDate = null;
       $lastLeg = $this->getLastLeg();
       if ($lastLeg instanceOf Leg) {
         $lastLeg->getStartDate();
       }
    
       return $lastLegDate;
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-11
      • 2011-04-29
      • 2011-03-28
      • 2012-04-02
      • 1970-01-01
      • 1970-01-01
      • 2021-12-08
      • 2010-11-30
      相关资源
      最近更新 更多