Skip to content

Instantly share code, notes, and snippets.

@dikiwidia
Created July 2, 2020 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dikiwidia/89eba2863c53f42a6f78a4ee6a9d9d9e to your computer and use it in GitHub Desktop.
Save dikiwidia/89eba2863c53f42a6f78a4ee6a9d9d9e to your computer and use it in GitHub Desktop.
Sum Array Value of Duplicate Data in PHP
<?php
/* -------------------------------------------------------------------------
Penjelasan sintaks: Digunakan untuk grouping array key "serial_no" sekaligus
mengakumulasi array key "qty" dengan "serial_no" yang sama.
---------------------------------------------------------------------------*/
$array = [
['serial_no' => '009-AZ', 'name' => 'BSI COIL Z009 1000-PCE', 'qty' => 91],
['serial_no' => '009-AZ', 'name' => 'BSI COIL Z009 1000-PCE', 'qty' => 20],
['serial_no' => '009-AZ', 'name' => 'BSI COIL Z009 1000-PCE', 'qty' => 102],
['serial_no' => '049-BZ', 'name' => 'GEM COIL Z100 0900-CSE', 'qty' => 91],
['serial_no' => '019-PG', 'name' => 'PGI COIL GL02 0922-ZEE', 'qty' => 18],
];
echo "<pre>";
print_r($array);
function unique_multidim_array($array, $key, $addedKey) {
$temp_array = [];
$key_array = [];
$i = 0;
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}else{
$pkey = array_search($val[$key],$key_array);
$temp_array[$pkey][$addedKey] += $val[$addedKey];
// die;
}
$i++;
}
return $temp_array;
}
$nArray = unique_multidim_array($array,"serial_no","qty");
// die;
echo "<br>";
print_r($nArray);
die;
echo "</pre>";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment