我正在尝试获取for循环中最后一次迭代的$ row->价格值,如下所示
foreach ($getprices->result() as $row)
{
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
我确实尝试了以下操作,但它似乎无法正常工作
$numItems = count($getprices->result());
$i = 0;
foreach($getprices->result() as $row) {
if(++$i === $numItems) {
if ($bb=='on'){
$pric = $row->price+2.50;
$pri = number_format($pric,2);
}else{
$pric = $row->price;
$pri = number_format($pric,2);
}
}
}
有什么建议吗?
答案 0 :(得分:3)
在循环结束后立即使用$row->price
:
foreach ($getprices->result() as $row)
{
// ...
}
$lastprice = $row->price;
这真的只是一个技巧,但它会起作用。如果你在迭代一个数组,你也可以这样做:
$array = $getprices->result();
foreach ($array as $row)
{
// ...
}
$lastprice = end($array)->price; // this will work independently of any loop
答案 1 :(得分:1)
在for语句后面添加一行$lastitem=$row
;它将包含循环结束后的最后一个值
答案 2 :(得分:1)