search

Home  >  Q&A  >  body text

Group by group, calculate the sum of occurrences of each group, and print the data as a formatted string

<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>
P粉970736384P粉970736384503 days ago521

reply all(1)I'll reply

  • P粉323050780

    P粉3230507802023-09-06 09:57:01

    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:

    Array
    (
        [FA] => Array
            (
                [12.9] => 3
                [12.4] => 1
            )
    
        [FB] => Array
            (
                [12.2] => 1
                [12.9] => 1
            )
    
        [FC] => Array
            (
                [12.3] => 1
            )
    
    )

    reply
    0
  • Cancelreply