[英]Codeigniter Model foreach return just single record
我們在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;
}
視圖
<?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; ?>
它僅返回1個結果,因為在foreach的每個循環中,您都覆蓋$ result變量,因此您錯過了之前獲得的所有結果。
您需要使用一個數組而不是$result
並將該數組返回給控制器。
例如:
$result_array[] = $this->db->get()->result()
在循環之后,您需要返回數組:
return $result_array
在您的每次迭代代碼中,$ 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.