我想在我的网站上创建一个“所有内容”页面,这将是我的所有用户活动。所以我需要从两个表“images”和“user_favorites”制作sql并输出所有这个html设计
我的桌子结构:
用户
id
图片
id
user_id
image
description
date
user_favorites
id
date
我有 sql 查询
function users_everything($user_id)
{
$sql = "SELECT
i.description as text,
UNIX_TIMESTAMP(i.date) as image_date,
COALESCE ( imgcount.cnt, 0 ) as comments,
fav.id as favorite_id,
r.image as favorited_image,
u2.username as favorite_user,
t.image as favorite_user_image
FROM users u
LEFT JOIN images i ON i.user_id = u.id
LEFT JOIN images p ON p.id = (SELECT b.id FROM images AS b where u.id = b.user_id ORDER BY b.id DESC LIMIT 1)
LEFT JOIN (SELECT image_id, COUNT(*) as cnt FROM commentaries GROUP BY image_id ) imgcount ON i.id = imgcount.image_id
LEFT JOIN user_favorites fav ON fav.user_id = u.id
LEFT JOIN images r ON r.id = fav.image_id
LEFT JOIN users u2 ON u2.id = r.user_id
LEFT JOIN images t ON t.id = (SELECT b.id FROM images AS b where u2.id = b.user_id ORDER BY b.id DESC LIMIT 1)
WHERE i.user_id = ?
";
$query = $this->db->query($sql, $user_id);
return $query->result_array();
}
我的“图片”表有1条记录和“user_follow”2条记录,但是如果我做了foreach它返回两个收藏夹并且两个图像(图像)被复制。
我不会像之前的所有页面那样将不同页面的数据呈现给不同的html结构。我想你有经验并帮助我
答案 0 :(得分:1)
您需要将平面记录数组转换为树结构,其中每个图像都包含收藏夹列表。类似的东西:
$images = array();
foreach($everything_list as $item)
{
// Check to see if already encountered this image
$imageId = $item['image_id'];
if (!isset($images[$imageId]))
{
// New image
$image = array();
// Do this for each image attribute
$image['image_id'] = $item['image_id'];
$image['favorites'] = array();
$images[$imageId] = $image;
}
// Add Favorite
$favorite = array();
// Do this for each favorite attribute
$favorite['favorite_id'] = $item['favorite_id'];
$images[$imageId]['favorites'][] = $favorite;
}
print_r($images);