简体   繁体   中英

Codeigniter Model foreach return just single record

we are using following code in Model , we are passing one text string with different ids of album, exlode, convert it to array and we are passing array ids in foreach and foreach return as 10 to 20 different albums result, but when we call this function from Controller, its return just single 1 records, whats wrong in code?

public function get_footer_links($album_ids) {
    $album_ids = explode(',', $album_ids);
    foreach ($album_ids as $album_id) {

        $this->db->select('ci_albums.album_name, ci_albums.album_slug, ci_categories.cat_slug'); 
        $this->db->from('ci_albums');
        $this->db->join('ci_categories', 'ci_categories.cat_id = ci_albums.cat_id' , 'left');
        $this->db->where('album_id', $album_id);
       $results = $this->db->get()->result();
    }

    return $results;
}

View

<?php foreach ($footer_links as $footer_links): foreach ($footer_links as $footer_link): ?>
       <a href="<?php echo site_url() . $footer_link->cat_slug .'/'. $footer_link->album_slug .'.html'; ?>" target="_blank"><?php echo ucwords($footer_link->album_name); ?></a> | 
    <?php endforeach; endforeach; ?>

It returns just 1 result because at every cycle of the foreach you override the $result variable and so you miss all the result you get before.
You need to use an array instead of $result and the return to the controller that array.

For example:

$result_array[] = $this->db->get()->result()

and after the loop you need to return the array:

return $result_array

In your code on each iteration $results is being replaced by the previous iteration of foreach loop, and that's why $results holds only one record.

public function get_footer_links($album_ids)
    {
        $album_ids = explode(',', $album_ids);
        $results = array();
        foreach ($album_ids as $album_id)
        {

            $this->db->select('ci_albums.album_name, ci_albums.album_slug, ci_categories.cat_slug');
            $this->db->from('ci_albums');
            $this->db->join('ci_categories', 'ci_categories.cat_id = ci_albums.cat_id', 'left');
            $this->db->where('album_id', $album_id);
            $result = $this->db->get()->result();
            array_push($results, $result);
        }

        return $results;
    }

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