Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

php array sum common values by key

<?php
  $data = array
  (
      0 => array("color"=> "red","val"=> 4),
      1 => array("color"=> "blue","val"=> 3),
      2 => array("color"=> "blue","val"=> 1)
  );

  $temp = [];
  foreach($data as $value) {
      //check if color exists in the temp array
      if(!array_key_exists($value['color'], $temp)) {
          //if it does not exist, create it with a value of 0
          $temp[$value['color']] = 0;
      }
      //Add up the values from each color
      $temp[$value['color']] += $value['val'];
  }

  header('Content-Type: application/json');
  print_r(json_encode($temp));
?>
 
PREVIOUS NEXT
Tagged: #php #array #sum #common #values #key
ADD COMMENT
Topic
Name
2+3 =