Group by group, calculate the sum of occurrences of each group, and print the data as a formatted string
P粉970736384
2023-09-05 22:43:27
<p>I want to group and sum the data of some rows based on the values of two columns. </p>
<p>My input is:</p>
<pre class="brush:php;toolbar:false;">$array = [
['FA',12.9],
['FA',12.9],
['FB',12.2],
['FC',12.3],
['FA',12.9],
['FB',12.9],
['FA',12.4],
];</pre>
<p>I want to print the grouped row values as a string, followed by a <code>x</code> and the total number of occurrences, in the following format: </p>
<pre class="brush:php;toolbar:false;">FA 12.9x3
FB 12.2x3</pre>
<p>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: </p>
<pre class="brush:php;toolbar:false;">$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;
}
}
}</pre>
<p>Can this code be optimized and printed in the correct format? </p>
<p>Desired output: </p>
<pre class="brush:php;toolbar:false;">FA 12.9x3
FB 12.2x1
FC 12.3x1
FB 12.9x1
FA 12.4x1</pre></p>
Using
array_reduce
In 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.Output: