gpt4 book ai didi

php - CodeIgniter:在 View 中显示两个表中的数据 - 使用一个循环?

转载 作者:行者123 更新时间:2023-11-29 13:21:56 24 4
gpt4 key购买 nike

我需要一些帮助。我有这两个数据库表,关系为 1-n(一张相册有很多图像):

  albums            images
---------- -------------
album_id img_id
title album_id
description img_file

现在我想做的是在我的 View 中显示所有相册及其图像,例如 this ,请参阅第二张屏幕截图(作品集)。

这是我 Controller 中的内容:

// fetch all album data 
$albums = $this->album_model->get();

// fetch images for each album
foreach ($albums as $album ) {
$images = $this->albumimage_model->get_by('album_id', $album->album_id);
}

$data = array(
'albums' => $albums,
'images' => $images,
);
$this->load->view('album_listing', $data);

如果我在 View 中循环浏览专辑数据,我会得到以下结果:

<?php foreach($albums as $album): ?>
<div class="album">
<p><?php echo $album->title; ?></p>
<p><?php echo $album->description; ?></p>
<div>
<?php endforeach; ?>

到目前为止一切顺利,但现在令人头痛的是:我想显示属于每个相册的图像,所以基本是这样的:

<?php foreach($albums as $album): ?>
<div class="album">
<p><?php echo $album->title; ?></p>
<p><?php echo $album->description; ?></p>

// show all images of the album
<div class="images"><img src="uploads/<php? echo $album->title; ?>.'/'.<php? echo $image->image_file; ?> " /></div>

<div>
<?php endforeach; ?>

根据 CodeIgniter 实践,我怎样才能做到这一点???

一些附加信息:1. 我还启用了 CodeIgntier 的 Profiler,并且我注意到正在运行的查询是这样递增的。如果我有很多相册(50 - 100 张带有图像的相册),这不会增加内存吗???

  1. 我还尝试仅使用一个带有 JOIN 的查询来完成此操作,如下所示:

    $albums = $this->db->select('albums.*') ->select('images.img_id, images.img_file') ->join('images', 'images.album_id = albums.album_id') ->order_by('专辑.album_id') ->get('专辑') ->result_array();

问题是当我循环访问数据时(假设我的数据库中有两个专辑),我在页面上获得了两次数据,例如:

album1 - images of album 1
album1 - images of album 1
album2 - images of album 2
album2 - images of album 2

最佳答案

$query = $this->db->get('albums');
$albums = $query->result_array();

$query = $this->db->get('images');
$images =$query->result_array();

foreach ($albums as $album)
{

foreach ($images as $image)
{
if($image['album_id'] == $album['album_id']){
$data[$album['album_id']]['images'] = $image['album_id'];
}
}
}

var_dump($data);

关于php - CodeIgniter:在 View 中显示两个表中的数据 - 使用一个循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20699851/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com