我们在模型中使用以下代码,我们传递一个具有不同 ID 的专辑的文本字符串,exlode,将其转换为数组,我们在 foreach 中传递数组 id,foreach 返回为 10 到 20 个不同的专辑结果,但是当我们从控制器调用这个函数时,它只返回单个 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;
}