Skip to content
Advertisement

PHP sum array value based on textual duplicate in another array

I have two arrays, both will always be the same count length. One has doubles mixed with integers, the second has textual (string only) values. They do correlate so I need them both to stay in order. Sorry no keys to work with (by design).

I need to sum the values where I have duplicates in the array that has strings.

Example

$dataLabelGraph = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding", "Coding");

So my algorithm should look like this after

$dataLabelGraph = array(21.86, 8, 1, 0.5);
$dataCalcGraph = array("Coding", "Web development - Coding", "Meeting", "Content");

I was trying to adapt this solution, from the awesome brain of Martin D. @ https://stackoverflow.com/a/22071693/12835769

$records_array = array("Coding", "Web development - Coding", "Meeting", "Coding", "Coding", "Content", "Coding");
$quantities_array = array(3, 8, 1, 4.85, 1, 0.5, 6.01, 7);
$new_array = array();
foreach ($records_array as $record_position => $new_array_key){
    $new_array[$new_array_key] += $quantities_array[$record_position];
}
var_dump($new_array);

Gives something like this, which is close but I need them to remain in two separate arrays

array (size=4)
  'Coding' => float 21.86
  'Web development - Coding' => int 8
  'Meeting' => int 1
  'Content' => float 0.5

Any help to get me over the line would be immensely helpful. Kudos.

Advertisement

Answer

Group by the “name” and sum as you iterate. When the loop is finished, split the keys and the values into separate arrays.

Code: (Demo)

$records = [
    "Coding",
    "Web development - Coding",
    "Meeting",
    "Coding",
    "Coding",
    "Content",
    "Coding",
    "Coding"
];
$quantities = [
    3,
    8,
    1,
    4.85,
    1,
    0.5,
    6.01,
    7
];

$result = [];
foreach ($records as $index => $label){
    $result[$label] = ($result[$label] ?? 0) + $quantities[$index];
}
var_export(array_keys($result));
var_export(array_values($result));

Outputs:

array (
  0 => 'Coding',
  1 => 'Web development - Coding',
  2 => 'Meeting',
  3 => 'Content',
)

array (
  0 => 21.86,
  1 => 8,
  2 => 1,
  3 => 0.5,
)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement