Group by group, calculate the sum of occurrences of each group, and print the data as a formatted string
P粉970736384
P粉970736384 2023-09-05 22:43:27
0
1
421

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

P粉970736384
P粉970736384

reply all (1)
P粉323050780

Usingarray_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:

Array ( [FA] => Array ( [12.9] => 3 [12.4] => 1 ) [FB] => Array ( [12.2] => 1 [12.9] => 1 ) [FC] => Array ( [12.3] => 1 ) )
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!