I want to group and sum some rows of data based on two column values.
My input is:
$array = [
['FA',12.9],
['FA',12.9],
['FB',12.2],
['FC',12.3],
['FA',12.9],
['FB',12.9],
['FA',12.4],
];
I want to print the grouped row values as a string then an x
and the total number of occurrences like this:
FA 12.9x3
FB 12.2x3
I have written code to count the occurrence of values in each group, but I'm unable to figure out how to print it in this format:
$new = [];
foreach ($array as $key=> $value) {
if (!array_key_exists($value[0],$new)) {
$new[$value[0]]=[strval($value[1])=>1];
}
else {
if (!array_key_exists(strval($value[1]),$new[$value[0]])) {
$new[$value[0]][strval($value[1])]=1;
// $no+=1;
}
else {
$count= $new[$value[0]];
$count=$count[strval($value[1])];
$count+=1;
$new[$value[0]][strval($value[1])]=$count;
}
}
}
Can this be optimized and printed in the correct format?
Desired output:
FA 12.9x3
FB 12.2x1
FC 12.3x1
FB 12.9x1
FA 12.4x1