0

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.

4
  • 1
    if (isset($sum2[$stat_name])) { /* do += */ } else { /* do = */ } Commented May 15, 2014 at 15:54
  • You want to sum all billed and route fields or sum the billed fields and then sum the routes fields or what? Commented May 15, 2014 at 15:55
  • Also, a print_r of array would help, as there is a much easier way. Commented May 15, 2014 at 16:01
  • @bwoebi that was EXACTLY what the problem was. Thank you very much Commented May 20, 2014 at 8:10

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'];
}

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.