我有一个foreach循环如下。
我正在寻找减去$ wrap-> wrap_total来自循环之前的那个并挣扎!
foreach ($wrap_query->result() as $wrap)
{
echo date("D d M Y", strtotime($wrap->wrap_date))." - ";
echo money_format('%n', $wrap->wrap_total)." - ";
echo "<br />";
}
当前输出如下:
2016年8月7日星期日 - 10,000.00英镑
2016年8月6日星期六 - 12,000.00英镑
2016年8月5日星期五 - £8,000.00
我想要的是:
2016年8月7日星期日 - 10,000.00英镑( - 2,000英镑)
2016年8月6日星期六 - 12,000.00英镑(4,000英镑)
2016年8月5日星期五 - £8,000.00
任何和所有帮助表示赞赏!
答案 0 :(得分:1)
以下评论代码可能会帮助您入门。演示文稿也可以找到here。
<?php
setlocale(LC_MONETARY, 'en_GB');
// LET US IMAGINE FOR A MOMENT THAT $wrap_query->result() CONTAINS
// THE FOLLOWING SIMULATED DATA MIMICKING YOUR DATA STRUCTURE...
$simulatedWrap1 = new stdClass();
$simulatedWrap2 = new stdClass();
$simulatedWrap3 = new stdClass();
$simulatedWrap1->wrap_date = "2016-08-07";
$simulatedWrap1->wrap_total = 10000.00;
$simulatedWrap2->wrap_date = "2016-08-06";
$simulatedWrap2->wrap_total = 12000.00;
$simulatedWrap3->wrap_date = "2016-08-05";
$simulatedWrap3->wrap_total = 8000.00;
$rWrapCollection = [
$simulatedWrap1,
$simulatedWrap2,
$simulatedWrap3,
];
// MAKE A COPY OF THE MAIN ARRAY COLLECTION
// THIS WOULD BE USED WITHIN THE LOOP TO MOVE THE ARRAY CURSOR
// TO THE NEXT ELEMENT WITHIN THE COLLECTION
$rWrapClone = $rWrapCollection;
// JUST FOR FUN: EXPLICITLY MOVE THE CURSOR TO THE FIRST
// ELEMENT IN THE COLLECTION
current($rWrapClone);
// CREATE AND INITIALIZE A VARIABLE $output TO AN EMPTY STRING.
// THIS VARIABLE WILL HOLD THE HTML CONTENT GENERATED WITHIN THE LOOP
$output = "";
foreach ($rWrapCollection as $index=>$wrap){
// MOVE THE CURSOR TO THE NEXT ITEM & CATCH THE VALUE IN A VARIABLE
$nextWrap = next($rWrapClone);
$output .= date("D d M Y", strtotime($wrap->wrap_date)) . " - ";
$output .= money_format('%n', $wrap->wrap_total);
// IF THERE IS STILL ANY NEXT ITEM, THEN CALCULATE
// THE DIFFERENCE BETWEEN THE CURRENT & NEXT ITEM
if($nextWrap){
$difference = $wrap->wrap_total - $nextWrap->wrap_total;
$output .= " (" . money_format('%n',$difference) . ")";
}
$output .= "<br />";
}
echo $output;
//PRODUCES:
Sun 07 Aug 2016 - £10,000.00 (-£2,000.00)
Sat 06 Aug 2016 - £12,000.00 (£4,000.00)
Fri 05 Aug 2016 - £8,000.00
与您的独特案例相关的有效代码:
<?php
$output = "";
$resultsCopy = $wrap_query->result();
current($resultsCopy);
foreach ($wrap_query->result() as $wrap) {
$nexWrap = next($resultsCopy);
$output .= date("D d M Y", strtotime($wrap->wrap_date)) . " - ";
$output .= money_format('%n', $wrap->wrap_total);
if($nexWrap){
$difference = $wrap->wrap_total - $nexWrap->wrap_total;
$output .= " (" . money_format('%n',$difference) . ")";
}
$output .= "<br />";
}
echo $output;
答案 1 :(得分:0)
随时跟踪上一个项目。如果有前一项(第一项后的所有结果)计算差值并在开始新线之前输出。
$previous = null;
foreach ($wrap_query->result() as $wrap) {
if ($previous) {
echo " (" .money_format('%n', $previous->wrap_total - $wrap->wrap_total) .")<br>";
}
echo date("D d M Y", strtotime($wrap->wrap_date))." - ";
echo money_format('%n', $wrap->wrap_total);
$previous = $wrap; // set previous to current
}