Jorg Ancrath
Jorg Ancrath

Reputation: 1447

PHP - add to values of multidimensional array

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.

Upvotes: 0

Views: 92

Answers (3)

mpyw
mpyw

Reputation: 5754

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

Upvotes: 1

Amal Murali
Amal Murali

Reputation: 76656

Easiest approach:

$arr = array(1,2,3);
$arrTotal[1][2][3] = array_sum($arr);

Upvotes: 8

francadaval
francadaval

Reputation: 2481

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

Upvotes: 0

Related Questions