Skip to content

Instantly share code, notes, and snippets.

@artofhuman
Created April 22, 2012 08:35
Show Gist options
  • Save artofhuman/2462745 to your computer and use it in GitHub Desktop.
Save artofhuman/2462745 to your computer and use it in GitHub Desktop.
sum arrays by keys
function array_mesh() {
// Combine multiple associative arrays and sum the values for any common keys
// The function can accept any number of arrays as arguments
// The values must be numeric or the summed value will be 0
// Get the number of arguments being passed
$numargs = func_num_args();
// Save the arguments to an array
$arg_list = func_get_args();
// Create an array to hold the combined data
$out = array();
// Loop through each of the arguments
for ($i = 0; $i < $numargs; $i++) {
$in = $arg_list[$i]; // This will be equal to each array passed as an argument
// Loop through each of the arrays passed as arguments
foreach($in as $key => $value) {
// If the same key exists in the $out array
if(array_key_exists($key, $out)) {
// Sum the values of the common key
$sum = $in[$key] + $out[$key];
// Add the key => value pair to array $out
$out[$key] = $sum;
}else{
// Add to $out any key => value pairs in the $in array that did not have a match in $out
$out[$key] = $in[$key];
}
}
}
return $out;
}
// Example
// $fbStats = $vkStats = array('id' => 'val')
$arSum = array_mesh($fbStats, $vkStats);
@m-waqas88
Copy link

You are awesome. You saved my day almost. God bless you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment