Search code examples
phparraysmultidimensional-arraysumunique

An array with sum and unique


First of all I'd like to thank you all for helping me out in this case. This is what I have no clue how to perform.

I have this while:

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, '.', ''));
}

And that while prints the following result:

[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
    )

What I've been trying to do is to create a new array with the result of:

if the base is RAO-ROO, I need to sum all yield values and divide by the amount of times I see the RAO-ROO to get an average yield result. And that goes for all other bases that may vary. In this case, it should be: RAO-ROO = (0.224 + 0.224 + 0.337) / 3 times it shows

I expect a result like:

[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
    )

So far I got this:

$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>";

Now I need to figure how to count how many times each base shows up and divide its yield to this amount of times to get an average.

Any help, please? Thank you again!


Solution

  • You have to group all the yields first, so you know how many to divide by, try something like this [TESTED]:

    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))));
    }