Round_Name = 'Round 1-6ren">
gpt4 book ai didi

php - 从 php 中的数组构建 "crosstab"或 "pivot"表

转载 作者:可可西里 更新时间:2023-10-31 22:08:40 24 4
gpt4 key购买 nike

我有一个类似于下面定义的对象数组:

$scores = array();

// Bob round 1
$s = new RoundScore();
$s->Round_Name = 'Round 1';
$s->Player_Name = 'Bob';
$s->Score = 10;
$scores[0] = $s;

// Bob round 2
$s = new RoundScore();
$s->Round_Name = 'Round 2';
$s->Player_Name = 'Bob';
$s->Score = 7;
$scores[1] = $s;

// Jack round 1
$s = new RoundScore();
$s->Round_Name = 'Round 1';
$s->Player_Name = 'Jack';
$s->Score = 6;
$scores[2] = $s;

// Jack round 2
$s = new RoundScore();
$s->Round_Name = 'Round 2';
$s->Player_Name = 'Jack';
$s->Score = 12;
$scores[3] = $s;

如果我遍历并将 $scores 对象转储到一个表中,它将看起来像这样:

Round_Name   Player   Score----------------------------Round 1      Bob        10Round 2      Bob         7Round 1      Jack        6Round 2      Jack       12

然而,我想要的是这样的:

Player  Round 1  Round 2  Total-------------------------------Bob       10        7       17Jack       6       12       18

我不会提前知道会有多少轮或玩家,我只能说我无法改变对象的构建方式。

在 php 中执行此操作的最有效方法是什么?

最佳答案

据我所知,PHP 数组是作为哈希表实现的(因此查找/更新应该非常有效)无论如何,时间效率会成为问题吗?

我会用“简单”的方式来做:

$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";
}

(我知道数组没有正确初始化,但你明白了)

关于php - 从 php 中的数组构建 "crosstab"或 "pivot"表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/712186/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com