【问题标题】:Foreach problem in controller - CodeIngiter控制器中的 Foreach 问题 - CodeIgniter
【发布时间】:2020-03-21 13:31:29
【问题描述】:

控制器“照片”:

public function seePics(){
        // in $res, i have all the pictures in my table 'photo' (id, id_photograph, title, size...)
        $res = $this->Photo_model->readPhoto();

        // with the session, i have all the data that i need on the connected user
        $this->load->library('session');
        $data = $this->session->userdata('data');

        // user id
        $idUser = $data['id'];

        // here, i want to have only the picture of the connected user
        if(!sizeof($res) == 0){
            foreach($res as $item){
                if($item->id_user == $idUser){
                    $values['photo'] = $item;
                    $this->load->view('photo/voirPhoto', $values);
                }       
            }
        }
        else{
            $this->load->view('photo/aucunePhoto',$data);
        }
    }

查看“voirPhoto.php”:我如何显示数据

<div class="row">
  <div class="col-md-6">
    <label>Title</label>
  </div>
  <div class="col-md-6">
    <p><?php echo $photo->titre?></p>
  </div>
</div>

<div class="row">
  <div class="col-md-6">
    <label>Name</label>
  </div>
  <div class="col-md-6">
    <p><?php echo $photo->name?></p>
  </div>
</div>

如您所见,我的 foreach 在我的控制器中,但我想在我的视图中执行 foreach。我该怎么做?

因为我的问题是:如果连接的用户有3张图片,它将显示3倍的视图。

提前致谢

【问题讨论】:

  • 为什么不自己过滤用户呢? $res = $this-&gt;Photo_model-&gt;readPhoto();

标签: php codeigniter foreach view controller


【解决方案1】:

就像 Viney 所说,您可以在 readPhoto 函数中的查询中过滤用户。 像这样的东西:$res = $this-&gt;Photo_model-&gt;readPhoto($idUser)

public function readPhoto($idUser = null) 
{
    $query = "select * from photos " . (($idUser)? "where id_user = {$idUser}" : "");

    ...
}

因此您将拥有已连接用户的所有照片。

如果您希望只捕获一行,您可以在查询中使用 $res[0] 或 first(取决于数据库)。

【讨论】:

  • 谢谢我试试
【解决方案2】:

控制器:

public function seePics($id=null){   
    $query['my_query'] = "Select * from photos where id _user =".$id; 
}

查看:

<?php foreach($my_query as $key=>$val){
   <?= $val['photo']?> //photo column name
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2018-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多