【问题标题】:Multiple Foreach Loop Codeigniter多个 Foreach 循环 Codeigniter
【发布时间】:2021-11-18 05:55:11
【问题描述】:

我想在不同的部分显示数据,但是运行时出错。

控制器

class Dfkamar extends CI_Controller {
public function index() {
    $data['tamu'] = $this ->m_tamu->daftar_kamar()->result();
        $this->load->view('templates/header');
        $this->load->view('templates/sidebar');
        $this->load->view('dfkamar', $data);
        $this->load->view('templates/footer');
}

查看

    <?php
      foreach ($tamu as $tamu) : 
    ?>

        <button type="button" class="btn btn-success"><?php echo $tamu->gateA ?></button>
      </div>  
      <?php endforeach;?>

    <?php
        foreach ($tamu as $tamu1) : 
      ?>

        <button type="button" class="btn btn-success"><?php echo $tamu1->gateB ?></button>
      </div>  
      <?php endforeach;?>

【问题讨论】:

  • 我会一直避免的事情是$tamu as $tamu,两次使用同一个变量是没有意义的。
  • 所以,只写$tamu?

标签: php codeigniter foreach codeigniter-3 foreach-loop-container


【解决方案1】:

$tamu 数组变量在第一次 foreach 中被替换 $tamu 字符串,所以不要这样做

工作代码如下:

$tamu = ['gateA'=>'test-A','gateB'=>'sdfs'];

      foreach ($tamu as $tamu_item) : 
        echo $tamu_item->gateA;
     endforeach;
     
     var_dump($tamu);

    foreach ($tamu as $tamu1) : 
        echo $tamu1->gateB;
     endforeach;

【讨论】:

  • $tamu = ['gateA'=>'test-A','gateB'=>'sdfs'];在控制器处替换还是什么?
  • foreach ($tamu as $tamu-> 在这里你定义了与数组相同的迭代项变量,因此在 foreach 数组替换为最后一项之后。
猜你喜欢
  • 2016-02-21
  • 2019-01-14
  • 1970-01-01
  • 2019-11-23
  • 1970-01-01
  • 2013-01-25
  • 1970-01-01
  • 2019-03-17
  • 1970-01-01
相关资源
最近更新 更多