构建“交叉表” 或“枢轴” php 中数组中的表
我有一个类似于以下定义的对象数组:
$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 10 Round 2 Bob 7 Round 1 Jack 6 Round 2 Jack 12
然而,我想要的是这样的:
Player Round 1 Round 2 Total ------------------------------- Bob 10 7 17 Jack 6 12 18
我不会提前知道会有多少轮或有多少玩家,只能说我无法改变对象的构造方式。
在 php 中执行此操作最有效的方法是什么?
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->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;
If I loop through and dump the $scores
object into a table, it will look something like this:
Round_Name Player Score ---------------------------- Round 1 Bob 10 Round 2 Bob 7 Round 1 Jack 6 Round 2 Jack 12
What I want, however, is something like this:
Player Round 1 Round 2 Total ------------------------------- Bob 10 7 17 Jack 6 12 18
I'm not going to know in advance how many rounds or players there'll be and let's just say I can't change the way the objects are constructed.
What's the most efficient way to do this in php?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,PHP 数组是作为哈希表实现的(因此查找/更新应该非常有效)
无论如何,时间效率会成为问题吗?
我会用“简单”的方式来做:(
我知道数组没有正确初始化,但你明白了)
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:
(I know the arrays aren't properly initialized, but you get the idea)
如果我们可以假设:
然后根据轮数,
然后,我们可以做的是在遍历数组时打印每个玩家的得分,同时计算过程中的总数,但如果我们看到新玩家则重置它:
示例输出:
这应该非常有效,因为它只遍历数组一次。
If we can assume that:
and then by the round number
Then, what we can do is print each player's score as we moved through the array while calculating the total in the process but resetting it if we see a new player:
Sample output:
This should be quite efficient because it only goes through the array once.