PHP calculate array data

I am having trouble to calculate the sum of an array values my array is

$bar_chart_data = 
array(
    array(
        array("Data1",548.25),
        array("Data2",238.75),
        array("Data3",95.50),
        array("Data4",300.50),
        array("Data5",286.80),
        array("Data6",148.25)
        )
    );

I am using this php code to calculate the results but its always gives me 0

$sumArray = array();
foreach ($bar_chart_data as $k=>$subArray) {
    foreach ($subArray as $id=>$value) {
        $sumArray[$id]+=$value;
    }
}

print_r($sumArray);

3 answers

  • answered 2018-01-11 19:38 Syscall

    Your $id is different in all iteration.

    You have to use $sumArray[$k]+=$value[1];.

    You also have to init $sumArray[$k] to 0 between your two foreach.

  • answered 2018-01-11 19:38 Faisal Alam

    I believe you have an array containing a sub-array and you want to get the sum of all the values in each of the sub-arrays.

    I suggest you use an associative sub-array to make the task easier.

    $bar_chart_data = array(
        array(
            "Data1" => 548.25,
            "Data2" => 238.75,
            "Data3" => 95.50,
            "Data4" => 300.50,
            "Data5" => 286.80,
            "Data6" => 148.25
        ),
        array(
    
        )
    );
    
    $sumArray = array(); // Create an empty array to store the sum of each sub-array
    foreach ($bar_chart_data as $subArray) {
        $sum = 0; // Initialize sum as zero
        foreach ($subArray as $key=>$value) {
            $sum += $value;
        }
        $sumArray[] = $sum; // Append each sum to the array
    }
    
    print_r($sumArray); // Print the array containing the sums.
    

  • answered 2018-01-11 19:38 AbraCadaver

    You only need one loop, then extract the values at index 1 and sum them:

    foreach($bar_chart_data as $values) {
        $sumArray[] = array_sum(array_column($values, 1));
    }
    

    You can add the $k => $values back and use $sumArray[$k] if needed, but the way your array is shown it will work without it.