简体   繁体   English

php中的关联数组值+=

[英]Associative array value += in php

I have an Invoice items list.我有一个发票项目列表。 I create a tax breakup array (associative array) to store unique tax percentages and their tax amount.我创建了一个税收分解数组(关联数组)来存储独特的税收百分比及其税额。

在此处输入图片说明

$taxbreakup=array(); 
@foreach($invoiceinfo->invoiceitems as $invoice_items)
    $taxbreakup[$invoice_items->tax_percentage]+=$invoice_items->tax_amount;
@endforeach

Group Tax percentage and display total tax amount for particular tax percentage分组税收百分比并显示特定税收百分比的总税额

在此处输入图片说明

@foreach($taxbreakup as $key => $value)
 
 <tr>

  <td colspan="12"></td>
  <td class="btmlft" colspan="2">GST ({{number_format($key,2)}})%</td>
  <td class="btmlft rghtbrd alignright">{{number_format(($value),2) }}</td>
  </tr>
 
 @endforeach

I got an undefined index error.我有一个未定义的索引错误。

In order to use += the variable you are accumulating the result into must be initialized, in your case it does not yet exist and is not initialized.为了使用+=将结果累加到的变量必须被初始化,在你的情况下它还不存在并且没有被初始化。

Even if you wanted to do即使你想做

$arr['val'] = $arr['val'] + 1;

the receiving variable need to have been created.需要创建接收变量。

So I would use所以我会用

$taxbreakup=array(); 
@foreach($invoiceinfo->invoiceitems as $invoice_items)
    // check accumulator exists before using it
    if ( ! isset($taxbreakup[$invoice_items->tax_percentage]) ) {
        $taxbreakup[$invoice_items->tax_percentage] = 0; 
    }
    $taxbreakup[$invoice_items->tax_percentage] += $invoice_items->tax_amount;
@endforeach
if ( ! isset($arr['hello']) ) { $arr['hello'] = 0; }

我认为这个变量 $taxbreakup 为空,检查 $taxbreakup 为空,然后执行 foreach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM