gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 09:53:57 24 4
gpt4 key购买 nike

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

end($collection)->getProperty()


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

没有工作

(告诉我我正在尝试在 bool 值上使用 getProperty())。
/**
* Get legs
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getLegs()
{
return $this->aLegs;
}

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

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

知道为什么吗?

最佳答案

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

Returns the value of the last element or FALSE for empty array.



所以改变你的代码如下:
$property = null

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

希望这有帮助

关于php - 获取集合中的最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32506828/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com