具有 sum 和 unique 的数组

An array with sum and unique

首先,我要感谢大家帮助我解决了这个问题。这是我不知道如何执行的。

我有一段时间了:

while($result = $s->fetch(PDO::FETCH_OBJ)){

    $Itinerario = $result->Itinerario;
    $Tarifa = $result->ValorTarifa;
    $Distancia = $result->DistanciaItinerario;

    $siglaBase = wordwrap($Itinerario, 3, "-", true);

    $novoArrayYield[] = array("base"=>$siglaBase, "yield"=>number_format(($Tarifa / $Distancia), 3, '.', ''));
}

同时打印出以下结果:

[0] => Array
    (
        [base] => RAO-ROO
        [yield] => 0.224
    )

[1] => Array
    (
        [base] => RAO-ROO
        [yield] => 0.224
    )

[2] => Array
    (
        [base] => RAO-ROO
        [yield] => 0.337
    )

[3] => Array
    (
        [base] => SJP-GRU-GRU-UDI-UDI-RAO-RAO-ROO
        [yield] => 0.132
    )

[4] => Array
    (
        [base] => BSB-RAO-RAO-ROO
        [yield] => 0.476
    )

[5] => Array
    (
        [base] => SJP-GRU-GRU-UDI-UDI-RAO-RAO-ROO
        [yield] => 0.176
    )

[6] => Array
    (
        [base] => GIG-RAO-RAO-ROO
        [yield] => 0.194
    )

我一直试图做的是创建一个新数组,其结果为:

如果基数是 RAO-ROO,我需要将所有屈服值相加并除以我看到 RAO-ROO 的次数以获得平均屈服结果。这适用于所有其他可能不同的基地。 在这种情况下,它应该是:RAO-ROO = (0.224 + 0.224 + 0.337) / 3 times it shows

我希望这样的结果:

[0] => Array
    (
        [base] => RAO-ROO
        [yield] => 0.261
    )

[1] => Array
    (
        [base] => SJP-GRU-GRU-UDI-UDI-RAO-RAO-ROO
        [yield] => 0.154
    )

[2] => Array
    (
        [base] => BSB-RAO-RAO-ROO
        [yield] => 0.476
    )

[3] => Array
    (
        [base] => GIG-RAO-RAO-ROO
        [yield] => 0.194
    )

到目前为止我得到了这个:

$newArray = array();
while ( $row = array_shift($novoArrayYield) ) {
     if ( !array_key_exists( $row['base'], $newArray ) ) {
            $newArray[$row['base']] = $row;
     } else {
            $newArray[$row['base']]['yield'] += $row['yield'];
     }
}
print "<pre>";
print_r( $newArray );
print "</pre>";

现在我需要弄清楚如何计算每个碱基出现的次数并将其产量除以该次数以获得平均值。

有什么帮助吗?再次感谢!

您必须先对所有收益率进行分组,这样您才能知道要除以多少,尝试这样的操作[已测试]:

while ( $row = array_shift($novoArrayYield) ) {

    $groupedBases[$row['base']][] = $row['yield'];
}

foreach ($groupedBases as $base => $yields) {

    var_dump(sprintf('Base: %s | Average: %2.3f', $base, (array_sum($yields) / count($yields))));
}