I want to group and sum the data of some rows based on the values of two columns.
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, followed by a x and the total number of occurrences, in the following format:
FA 12.9x3 FB 12.2x3
I've written code to count the occurrences of a value in each group, but I don't know how to print it out 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 code 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
Using
array_reduceIn a special and useful way, we can group items by name. Then group by value and count. The idea is to pass an array with accumulated values as keys.$g = array($a, $b, $c, $d, $e, $f, $h); $result = array_reduce($g, function ($carry, $item) { $key = $item[0]; $value = $item[1]; if (!isset($carry[$key])) { $carry[$key] = []; } if (!isset($carry[$key][(string) $value])) { $carry[$key][(string) $value] = 0; } $carry[$key][(string) $value]++; return $carry; }, []); print_r($result);Output: