Search code examples
phparraysmultidimensional-arraysummarize

Summarize the same key name in php multidimensional array


I have an array like this:

[0] => Array
            (
                [id_station] => 2397
                [hour] => 12
                [data] => Array
                    (
                        [cameraon] => 355654
                        [cameraoff] => 4532
                        [camerabroken] => 76745
                        ...
                    )
            )
[1] => Array
            (
                [id_station] => 2399
                [hour] => 13
                [data] => Array
                    (
                        [cameraon] => 3905466
                        [cameraoff] => 1672
                        [camerabroken] => 70780
                        ...
                    )
            )

I want to add one more row = total of all items

[1] => Array
            (
                [id_station] => 
                [hour] => 
                [data] => Array
                    (
                        [cameraon] => 4261120
                        [cameraoff] => 6204
                        [camerabroken] => 147525
                    )
            )

I used array_sum(array_column($array["data], 'cameraon')) but I have to do for all items cameraon, cameraoff, camerabroken (I have a hundred items).

Is there any way to get total row in this case?


Solution

  • I assume that you don't know the depth of data sub-array. (that is how many key-value pairs are there)

    So do like below:-

    $final_array = [];
    $final_array['id_station'] ='';
    $final_array['hour'] ='';
    foreach($original_array as $original_arr){
      foreach($original_arr['data'] as $key=>$original){
         $final_array['data'][$key] +=$original;
      }
    }
    

    Output:-https://eval.in/926729