Building a “crosstab” or “pivot” table from an array in php

后端 未结 2 1329
暖寄归人
暖寄归人 2021-01-06 06:14

I have an array of objects defined similarly to the below:

$scores = array();

// Bob round 1
$s = new RoundScore();
$s->Round_Name = \'Round 1\';
$s->         


        
2条回答
  •  醉酒成梦
    2021-01-06 06:58

    As far as I can tell, PHP arrays are implemented as hash tables (so lookup/update should be pretty efficient) Will time efficiency even be a problem, anyway?

    I would just do it the "simple" way:

    $table = array();
    $round_names = array();
    $total = array();
    
    foreach ($scores as $score)
    {
        $round_names[] = $score->Round_Name;
        $table[$score->Player_Name][$score->Round_Name] = $score->score;
        $total[$score->Player_Name] += $score->score;
    }
    
    $round_names = array_unique($round_names);
    
    foreach ($table as $player => $rounds)
    {
        echo "$player\t";
        foreach ($round_names as $round)
            echo "$rounds[$round]\t";
        echo "$total[$player]\n";
    }
    

    (I know the arrays aren't properly initialized, but you get the idea)

提交回复
热议问题