Search
 
SCRIPT & CODE EXAMPLE
 

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));
?>
Comment

PREVIOUS NEXT
Code Example
Php :: livewire mount return type 
Php :: markdown mail html rendering laravel 
Php :: cakephp 3 
Php :: codeigniter 4 multiple validate error 
Php :: an einem string etwas anfügen php 
Php :: Personnaliser le logo de connexion WordPress sans plugin 
Php :: laravel collection makeVisible 
Php :: js data php 
Php :: phpcs unabl 
Php :: laravel relationship example 
Php :: Cakephp api POST request , saving data without validation 
Php :: singular from table laravel 
Php :: wp plugin handles - load on specific page 
Php :: php curl fail verbosly 
Php :: onde que fica a praia escondida no roblox jo mulher maravilha 
Php :: MForm Bild Attribute 
Php :: way to convert an integer to an array of numbers 
Php :: avoid grouping databases in phpmyadmin 
Php :: namespace not working php 
Php :: php numeros enteros 
Php :: Laravel 9.x Target class does not exist error at login application 
Php :: html vs php 
Php :: how to validate email or phone number single parameter request in laravel 
Php :: php decrement variable by 1 
Php :: propel find index 
Php :: Trongate custom routing 
Php :: if($a $b){ echo "A B"; }else if($a < $b){ echo "A < B"; }else if($a != ""){ if($a == $b){ echo "A = B"; } } 
Php :: How to Filter Your Posts & Pages by Custom Field in WordPress Dashboard 
Php :: tutorial crud phpmyadmin 
Php :: laravel creating_table_name 
ADD CONTENT
Topic
Content
Source link
Name
2+9 =