在foreach PHP中使用echo时添加字符串

时间:2018-12-13 06:02:47

标签: php laravel

我正在使用foreach在laravel php中显示数据库中的某些值。但是,当我运行多个foreach语句时,这些值以单个值的形式出现,例如“ 100.00 200.00”。但是,我希望这些值是在foreach语句之后添加的字符串,例如“ 300.00”。我的foreach语句如下:

@php
foreach($cash_sales as $cs){
  if( $ledgers->id == $cs->dr_ledger){
    echo number_format($cs->amount, 2);
  };
};      

foreach($oprefund_credit_cr as $op){
  if( $receivable->id == $op->ledger_code){
    echo number_format($op->amount, 2);
  };
};
@endphp

我希望通过添加值来使用它们。有什么方法可以实现我想要的?任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

如果我的问题正确,请将中间结果存储在变量中,并在最后打印。

$sum = 0;
foreach($cash_sales as $cs){
  if( $ledgers->id == $cs->dr_ledger){
    sum += $cs->amount; 

  };
};      

foreach($oprefund_credit_cr as $op){
  if( $receivable->id == $op->ledger_code){
    echo number_format($op->amount, 2);
    $sum+=$op->amount;
  };
};
echo number_format($sum, 2);

编辑:

这应在每个分类账中保存单个金额

$result = [];

foreach($cash_sales as $cs){
  if( $ledgers->id == $cs->dr_ledger)
  {
       $key = 'cash_sales_'.$cs->dr_ledger;
       if (empty($result[$key]) $result[$key] = 0; 
       $result[$key] += $cs->amount; 

  };
};      

foreach($oprefund_credit_cr as $op){
  if( $receivable->id == $op->ledger_code){
    $key = 'oprefund_credit_cr_'.$op->ledger_code;
    if (empty($result[$key]) $result[$key] = 0; 
    $result[$key] += $cs->amount; 
  };
};


foreach($result as $key=>$value)
{
    echo sprintf("%s: %s", $key, number_format($value, 2));
}

答案 1 :(得分:0)

您可以维护2个变量,一个用于Dr,另一个用于Cr。然后对它们求和,并echo仅在循环结束后一次。

@php
$sumDr = 0;
foreach($cash_sales as $cs){
  if( $ledgers->id == $cs->dr_ledger){
    $sumDr += $cs->amount;
  };
};

echo 'Dr Ledger=' . number_format($sumDr, 2);

$sumCr = 0;
foreach($oprefund_credit_cr as $op){
  if( $receivable->id == $op->ledger_code){
    $sumCr += $op->amount;
  };
};

echo 'Cr Ledger=' . number_format($sumCr, 2);
@endphp 

答案 2 :(得分:0)

可以请您尝试以下解决方案。如果您有字符串,请在操作前爆炸。见下文

@php
$tempSum = array();
$cash_sales = explode(',', $cash_sales);
$oprefund_credit_cr = explode(',', $oprefund_credit_cr)

foreach($cash_sales as $csKey => $cs){
  if( $ledgers->id == $cs->dr_ledger){
    $tempSum[$csKey][] = $cs->amount;
  };
};

foreach($oprefund_credit_cr as $opKey => $op){
  if( $receivable->id == $op->ledger_code){
    $tempSum[$opKey][] = $op->amount;
  };
};

if(!empty($tempSum))
{   
    foreach($tempSum as $temp_result) {
        if( !empty($temp_result) && count($temp_result) > 0 ){
            $sum = 0;
            foreach($temp_result as $temp) {
                $sum += $temp;
            }
            echo number_format($sum, 2);
        };
    };  
}
@endphp