简体   繁体   English

Codeigniter模型foreach仅返回单个记录

[英]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? 我们在Model中使用以下代码,我们传递一个带有不同专辑ID的文本字符串,展开,将其转换为数组,并在foreach中传递数组ID,foreach返回10到20个不同专辑的结果,但是当我们调用此字符串时来自Controller的函数,它仅返回单个1条记录,代码有什么问题?

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. 它仅返回1个结果,因为在foreach的每个循环中,您都覆盖$ result变量,因此您错过了之前获得的所有结果。
You need to use an array instead of $result and the return to the controller that array. 您需要使用一个数组而不是$result并将该数组返回给控制器。

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. 在您的每次迭代代码中,$ results都被foreach循环的上一个迭代所替代,这就是$ results仅保存一条记录的原因。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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