gpt4 book ai didi

php - Codeigniter foreach View 表布局

转载 作者:可可西里 更新时间:2023-11-01 08:29:50 24 4
gpt4 key购买 nike

努力构建 html 表格布局。这是我要显示的内容:

Player | Week 1 | Week 2 | Week 3
1 | 11 | 19 | 7
2 | 14 | 12 | 10
3 | 9 | 15 | 13

但这就是我所能得到的:

Player | Week 1 | Week 2 | Week 3
1 | 11 | |
1 | 19 | |
1 | 7 | |
2 | 14 | |
2 | 12 | |
2 | 10 | |
3 | 9 | |
3 | 15 | |
3 | 13 | |

这些值来自一个表(results),其中包含“Player”、“Week”和“Score”列

这是模型中的函数:

public function get_results(){
for($plyr=1;$plyr<3;$plyr++) {
$this->db->select('player, week, score');
$this->db->from('results');
$this->db->group_by(array('player','week'));

$query = $this->db->get();
return $query->result();
}
}

这是 View :

<?php foreach($results as $result) : ?>
<tr>
<td><?php echo $result->player; ?></td>
<td><?php echo $result->score; ?></td>
</tr>
<?php endforeach; ?>

我不知道如何循环显示它,如上所示。我尝试在 View 中嵌套 foreach 循环,但没有成功。无法想象嵌套的 foreach 如何在模型函数中工作,特别是因为我只希望玩家 # 只迭代一次,而他们的每个每周得分都在同一行中。

编辑:我让表格更清晰

最佳答案

透视结果

如果你总是有 3 周,你可以通过使用条件聚合来获得每周的分数来调整你的结果

  $this->db->select("player, 
sum(case when week = 'Week 1' then score end) 'Week 1',
sum(case when week = 'Week 2' then score end) 'Week 2',
sum(case when week = 'Week 3' then score end) 'Week 3'");
$this->db->from('results');
$this->db->group_by('player');
$query = $this->db->get();
return $query->result();

备选方案:用 PHP 重新索引数据

另一种解决方案是保留当前查询并首先按玩家然后按周重新索引 php 中的数据,以便每个 player,week 键都映射到 score .

$resultsByPlayer = array();

foreach($results as $result) {
$resultsByPlayer[$result->player][$result->week] = $result->score;
}

foreach($resultsByPlayer as $player => $resultsByWeek) {
print "<tr><td>$player</td>";
ksort($resultsByWeek);
foreach($resultsByWeek as $week => $score) {
print "<td>$score</td>";
}
print "</tr>";
}

关于php - Codeigniter foreach View 表布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30020136/

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