PHP数组前的求和键



我一直试图以特定的方式与我的数组工作,但没有成功。我试了很多不同的例子,但没有人帮助我。

$SelectDiaSPReceita打印出数千个这样的结果:

[0] => Array
    (
        [Origem] => VDC
        [Destino] => GRU
        [DataHoraVenda] => 2015-09-01 00:02:00.000
        [TotalEmissao] => 867.6800
    )

$arrayDiaSP = array();
foreach ($SelectDiaSPReceita as $value) {
    $hora = substr( $value['DataHoraVenda'] , 11, -10);
    $dia = substr( $value['DataHoraVenda'] , 8, -13);
    $mes = substr( $value['DataHoraVenda'] , 5, -16);
    $ano = substr( $value['DataHoraVenda'] , 0, -19);
    if(isset($arrayDiaSP[$hora])):
        $arrayDiaSP[$hora]['BilhetesVendidos']++;
        $arrayDiaSP[$hora]['TarifaTotal'] += $value['TotalEmissao'];
    else:
        $arrayDiaSP[$hora] = array( "Dia" => $dia, "Mes" => $mes, "Ano" => $ano, "Hora" => $hora, "BilhetesVendidos" => 1, "TarifaTotal" => number_format($value['TotalEmissao'], 2) );
    endif;
}

这是我创建的数组,它输出如下内容:

[00] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 00
        [BilhetesVendidos] => 81
        [TarifaTotal] => 20285.77
    )
[01] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 01
        [BilhetesVendidos] => 27
        [TarifaTotal] => 6733.52
    )
[02] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 02
        [BilhetesVendidos] => 11
        [TarifaTotal] => 4088.1
    )
直到…

[23] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 23
        [BilhetesVendidos] => 80
        [TarifaTotal] => 23730.35
    )

每个键代表一天中的一个小时。我要做的是将当前键和之前键的BilhetesVendidosTarifaTotal相加。如:

[00] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 00
        [BilhetesVendidos] => 81
        [TarifaTotal] => 20285.77
    )
[01] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 01
        [BilhetesVendidos] => 108
        [TarifaTotal] => 27019.29
    )
[02] => Array
    (
        [Dia] => 01
        [Mes] => 09
        [Ano] => 2015
        [Hora] => 02
        [BilhetesVendidos] => 119
        [TarifaTotal] => 31107,39
    )

等等…直到最后一把钥匙。它的意思是:

key 00 = key 00
key 01 = key 00 + key 01
key 02 = key 01 + key 02
...
请帮忙好吗?谢谢你!

这是你想要的吗?

$bilhetesVendidos = 0;
$tarifaTotal      = 0;
foreach ($arrayDiaSP as &$entry) {
    $bilhetesVendidos += $entry['BilhetesVendidos'];
    $tarifaTotal      += $entry['TarifaTotal'];
    $entry['BilhetesVendidos'] = $bilhetesVendidos;
    $entry['TarifaTotal']      = $tarifaTotal;
}

对数值求和,并将每小时的BilhetesVendidosTarifaTotal替换为之前所有条目的和。

如果您只想对当前和以前的值求和而不影响后续条目,则需要使用不同的方法。

相关内容

  • 没有找到相关文章

最新更新