简体   繁体   中英

Can't retrieve values from foreach loop under CodeIgniter

I can't retrieve values from $info (as stated below) in CodeIgniter View.

Here is the scenario: I explained everything the code.

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.

using $result inside foreach is not reasonable. Because in each loop $result will take a new value. So, preferably use it as an array and then pass it to your view. Besides, you should not use return inside 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);
}

to check what $result array has do var_export($result); or var_dump($result); after the end of foreach . and make sure that this is what you want to send to your view.

Now, in your view you can do:

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

//process

<?php endforeach;?>

Please remove return statement from

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

now $info can be access in view.

hope this will help you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM