【问题标题】:Codeigniter foreach view table layoutCodeigniter foreach 视图表布局
【发布时间】:2015-07-13 05:58:21
【问题描述】:

努力构建 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),其中包含“玩家”、“周”和“分数”列

这是模型中的函数:

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();
    }   
}   

这里是视图:

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

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

编辑:我让表格更清晰

【问题讨论】:

    标签: php mysql foreach codeigniter


    【解决方案1】:

    透视结果

    如果您总是有 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>";
    }
    

    【讨论】:

    • 感谢您的回复,我应该更具体一些。我将有超过 3 周的时间 - 总共超过 20 周。我不反对建立 20 个案例,但是没有办法循环这个吗?
    • 尝试了替代方案,得到:不能使用 stdClass 类型的对象作为数组尝试通过它...
    • 错误无法使用 stdClass 类型的对象,因为在线收到数组:$resultsByPlayer[$result['Player']][$result['week']] = $result['score'] ; ...不知道如何解决这个问题。有什么想法吗?
    • FuzzyTree - 谢谢!现在工作!我不能赞成答案 - 我显然没有足够的经验值。一旦我这样做,我会回来支持这个。再次感谢!!!
    • 从您的数据库设计中,您必须更改在这种情况下应用的逻辑。对您的数据库表或Result 模型的每个查询都应该只获取所有周以及按周排序的单个玩家的相应分数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-08
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    相关资源
    最近更新 更多