从foreach对象数据中获取最后的数据

时间:2016-09-20 03:55:44

标签: php mysql codeigniter codeigniter-3

如何从foreach获取最后的数据,我想保存最后的数据到结果,

结果图片:

结果

enter image description here

<?php
$s_kredit   = 0;
foreach ($ju as $j ) {
                $s_debet += $j->debet   - $j->kredit;
                $s_kredit += $j->kredit - $j->debet;
<tr>
<td class="center"><?php if(@$set_saldo->debet==0) { echo "-"; } else { echo number_format($s_debet,0,".","."); } ;?></td>
<td class="center"><?php if(@$set_saldo->kredit==0) { echo "-"; } else { echo number_format($s_kredit,0,".","."); } ;?></td>
</tr>

4 个答案:

答案 0 :(得分:2)

您应该使用end功能。

  

end - 将数组的内部指针设置为最后一个元素

$array=[3,4,5,8];    
echo end($array); // 8

答案 1 :(得分:1)

<?php 
$data=array(1,3,4,5,6,7,7);
$last = $data[count($data) - 1]; 
?>

答案 2 :(得分:0)

<?php
// ok try it nothing else, every loop change $last value, & when loop end, last variable will stored in the $last. 
$s_kredit   = 0;
$last = '';
foreach ($ju as $j ) {
            $s_debet += $j->debet   - $j->kredit;
            $s_kredit += $j->kredit - $j->debet;
            $last = $j;
<tr>
<td class="center"><?php if(@$set_saldo->debet==0) { echo "-"; } else { echo    number_format($s_debet,0,".","."); } ;?></td>
<td class="center"><?php if(@$set_saldo->kredit==0) { echo "-"; } else {    echo number_format($s_kredit,0,".","."); } ;?></td>
</tr>

答案 3 :(得分:0)

创建另一个变量

<?php
$s_kredit   = 0;
$s_final   = 0;
foreach ($ju as $j ) {
                $s_debet += $j->debet   - $j->kredit;
                $s_kredit += $j->kredit - $j->debet;
                $s_final = $j->kredit;
<tr>
<td class="center"><?php if(@$set_saldo->debet==0) { echo "-"; } else { echo number_format($s_debet,0,".","."); } ;?></td>
<td class="center"><?php if(@$set_saldo->kredit==0) { echo "-"; } else { echo number_format($s_kredit,0,".","."); } ;?></td>
</tr>
}

// show $s_final after the loop