获取集合中的最后一个元素

Pie*_*ran 2 php collections doctrine symfony doctrine-collection

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

end($collection)->getProperty()
Run Code Online (Sandbox Code Playgroud)

$collection->last()->getProperty()
Run Code Online (Sandbox Code Playgroud)

没有办法

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

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

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

    return $legs->last()->getStartDate();
}
Run Code Online (Sandbox Code Playgroud)

知道为什么吗?

Mat*_*teo 6

您有问题是由于集合为空。在内部该last()方法使用来自docend()php函数:

返回空数组的最后一个元素的值或FALSE。

因此,如下更改代码:

$property = null

if (!$collection->isEmpty())
{
$property =  $collection->last()->getProperty();
}
Run Code Online (Sandbox Code Playgroud)

希望这个帮助