Pergunta

I have 3 level nested array and I would like some help to make the generate the sum of its values. The array goes like

                                    SUM
                                 /       \
                               A          B
                              / \         /\
                        Billed  Route Billed Route
                         /        \      /      \
                       Value     Value  Value    Value

How can i make a sum of the Billed and Route fields?

So far I have this code

foreach($sum as $client)
            {

                $s = 0;
                foreach($client as $stat_name=>$stat_value)
                {
                    $val = 0;
                    // echo "<br><u><i>";
                    // echo $stat_name;
                    // echo "</u></i><br>";
                    foreach($stat_value as $value)
                    {
                        $val += intval($value);
                    }
                    $sum2[$stat_name] += $val;
                }

            }

I receive an undefine index error on the first loop for each new key.

Foi útil?

Solução

Have you defined $sum2[$stat_name] as 0 ? If not, you'll get an undefined index error on each iteration of the second foreach loop because you're trying to do += on a value that isn't defined.

Also, if you're trying add the values of Billed and Route then storing them in different parts of an associative array ($sum2[$stat_name]) is an extra step. Just add them together in the same key of the array.

Outras dicas

If those are the actual keys in your array, then:

$route = 0;
$billed = 0;
foreach($yourarray['SUM'] AS $ab => $subarray) {
   $billed += $subarray['Billed']['Value'];
   $route  += $subarray['Routed']['Value'];
}
$sum2[$stat_name] += $val;

is the same as:

$sum2[$stat_name] = $sum2[$stat_name] + $val;
                    ^^^^^^^^^^^^^^^^^ undefined the first time you loop

To solve that, you should initialize it:

$sum2[$stat_name] = isset($sum2[$stat_name]) ? $sum2[$stat_name] : 0;
$sum2[$stat_name] += $val;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top