phparraysmultidimensional-arraysumgrouping

Sum all "grandchild" values in a multidimensional array to create a flat associative array


Can someone please explain how to obtain the total of the values coming under each of the two outer array elements? I want to end with an array showing the values for each date Nov 18, 2011 and Nov 22, 2011. Here is the array data:

[
    'Nov 18, 2011' => [
        'C' => [
            'T' => 49783.531672,
            'X' => 25013.184
        ],
        'S' => [
            'T' => 32908.863528
        ],
        'I' => [
            'T' => 44561.52
        ]
    ],
    'Nov 22, 2011' => [
        'C' => [
            'T' => -5168.944696
        ],
        'S' => [
            'T' => -3823.890504
        ]
    ]
]

Solution

  • A script would be:

    $results = array();
    foreach($array as $element){
        $sum = 0;
        foreach($element as $subelement){
            foreach($subelement as $item => $value){
                $sum = $sum + $value;
            }
        }
        array_push($results, $sum);
    }
    

    This would give you an array of the sums. You could of course name each if you so desired and so on.

    Edit: Got ahead of myself. Edited to me sum, not count