【问题标题】:Can't retrieve values from foreach loop under CodeIgniter无法从 CodeIgniter 下的 foreach 循环中检索值
【发布时间】:2013-01-03 01:07:47
【问题描述】:

我无法在 CodeIgniter 视图中从 $info(如下所述)检索值。

这是场景: 我用代码解释了一切。

function info() {
{...} //I retrieve results from database after sending $uid to model.
    $dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value.


    foreach($dbresults as $row) {
        $info = $row->address; //This is what I need to produce the results
        $results = $this->my_model->show_info($info);

    return $results; //This is my final result which can't be achieved without using $row->address. so first I have to call this in my controller.

    }

    // Now I want to pass it to a view

    $data['info'] = $results;
    $this->load->view('my_view', $data);

    //In my_view, $info contains many values inherited from $results which I need to call one by one by using foreach. But I can't use $info with foreach because it is an Invalid Parameter as it says in an error.

【问题讨论】:

    标签: php codeigniter foreach codeigniter-2 variable-assignment


    【解决方案1】:

    foreach 中使用$result 是不合理的。因为在每个循环中 $result 都会取一个新值。因此,最好将其用作array,然后将其传递给您的视图。此外,您不应该在foreach 中使用return

    function info() {
    {...} //I retrieve results from database after sending $uid to model.
        $dbresults = $this->my_model->get_info($uid); //Assume that this model returns some value
    
    $result = array();
        foreach($dbresults as $row) {
            $info = $row->address; //This is what I need to produce the results
            $result[] = $this->my_model->show_info($info);
    
        }
    
        // Now I want to pass it to a view
    
        $data['info'] = $result;
        $this->load->view('my_view', $data);
    }
    

    检查 $result 数组在 foreach 结束后对 var_export($result);var_dump($result); 做了什么。并确保这是您想要发送到您的视图的内容。

    现在,在您看来,您可以这样做:

    <?php foreach ($info as $something):?>
    
    //process
    
    <?php endforeach;?>
    

    【讨论】:

      【解决方案2】:

      请从

      中删除return声明
      foreach($dbresults as $row) {
          $info = $row->address; //This is what I need to produce the results
          $results[] = $this->my_model->show_info($info);
          //  return $results; remove this line from here;
      }
      
      $data['info'] = $results; // now in view access by $info in foreach
      $this->load->view('my_view', $data);
      

      现在 $info 可以在视图中访问了。

      希望对您有所帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-21
        • 2022-01-14
        • 1970-01-01
        相关资源
        最近更新 更多