Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get sum of php multidiamentional array

I am looking to store sum of all keys inside an array here is my example code

<?php

// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {
    
                list($sale_key, $sale_value) = explode('*', $value);
                $category->sale_data[$sale_key][] = $sale_value;
                //$category->sale_data_sum[$sale_key][] += $sale_value;
}
// display
print_r($category);

getting this output working example -> https://3v4l.org/NAKfb#v7.0.0

Here is expected to get //$category->sale_data_sum[$sale_key][] +=
$sale_value;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am expected output like this

stdClass Object
(
    [category_name] => 32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1
    [sale_data] => Array
        (
            [32459] => Array
                (
                    [0] => 1500
                )

            [32460] => Array
                (
                    [0] => 400
                )

            [32461] => Array
                (
                    [0] => 600
                )

        )
    [sale_data_sum] => 2500

)

>Solution :

Simply do this:

$category->sale_data_sum = 0; // initiate key
foreach ($category_sale_data as $key => $value) {
    list($sale_key, $sale_value) = explode('*', $value);
    $category->sale_data[$sale_key][] = $sale_value;
    $category->sale_data_sum += $sale_value; // add each sale value
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading