无法从CodeIgniter下的foreach循环中检索值

时间:2013-01-19 11:34:15

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

我无法从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.

2 个答案:

答案 0 :(得分:3)

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

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

var_export($result);结束后查看$ result数组{1 var_dump($result);foreach。并确保这是您要发送到视图的内容。

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

<?php foreach ($info as $something):?>

//process

<?php endforeach;?>

答案 1 :(得分:1)

请从

中删除返回声明
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。

希望这会对你有帮助!