0

I basically want to change the value of a multidimensional array by adding to the previous value.

Example:

$arr=array(1,2,3);

foreach($arr as $val){
    $arrTotal[1][2][3]=$val;
}

This would make $arrTotal[1][2][3]=3

What I really want is $arrTotal[1][2][3]=6

3+2+1.

I have tried an approach like so:

$arrTotal[1][2][3]+=$val;

But to no avail.

3 Answers 3

8

Easiest approach:

$arr = array(1,2,3);
$arrTotal[1][2][3] = array_sum($arr);
Sign up to request clarification or add additional context in comments.

Comments

1

More general solution:

<?php

function hierarchical_array_sum(array $arr) {
    $parent = null;
    $current = $total = new ArrayObject;
    foreach ($arr as $val) {
        $parent = $current;
        $current = $current[$val] = new ArrayObject;
    }
    if ($parent !== null) {
        $parent[$val] = array_sum($arr);
    }
    $total = json_decode(json_encode($total), true);
}

var_dump(hierarchical_array_sum(array(1, 2, 3, 4, 5, 6, 7)));

Comments

0
$arrTotal[1][2][3] = 0;
foreach($arr as $val){
    $arrTotal[1][2][3] = $arrTotal[1][2][3] + $val;
}

1 Comment

Not the easiest approach ;-)

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.