PHP数组求和键之前

时间:2015-09-03 22:25:08

标签: php arrays multidimensional-array sum key

我一直试图以特定方式使用我的阵列,但没有成功。我尝试了很多不同的例子,但我没有人帮助过我。

$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
...

请帮忙吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

这是你想要的吗?

$bilhetesVendidos = 0;
$tarifaTotal      = 0;

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

    $entry['BilhetesVendidos'] = $bilhetesVendidos;
    $entry['TarifaTotal']      = $tarifaTotal;
}

它汇总了值,并将每小时的BilhetesVendidosTarifaTotal替换为所有先前条目的总和。

如果您只想总结当前值和之前的值而不影响后续条目,则需要采用不同的方法。