PHP ve MySQL kullanıyorum. Ben fotoğrafları bir tablo var. fotoğraflar tablo var: fotoğraf için bir bağlantı, bir category_id, tarih.
What would be the best way to list all the categories on the page with the newest 20 photos under each?
Şu anda tüm fotoğrafları seçiyorum ve sonra PHP sonra bunları çözmek. Bir kategoride 500 resimleri var alırsa bu çok verimsiz görünüyor. Herhangi bir daha bunun SQL sonu için fikir?
Ben düşündüm diğer tek yolu, döngü her bir kategori için 20 sınırı sorgu oldu, ama 100 kategoriler varsa daha da kötü görünüyor!
pseudo output
[category_list] => {
[0]=> {
'category_title' => 'photos at sunset',
'posts' => {
[0] => {
'photo_link' = '1.jpg',
}
[1] => {
'photo_link' = '2.jpg',
}
}
}
[1]=> {
'category_title' => 'photos at sunrise',
'posts' => {
[0] => {
'photo_link' = '1.jpg',
}
}
}
}
pseudo code
$query =
"
SELECT
photographs.category_id, photographs.photo_link, categories.title
FROM
photographs
INNER JOIN
categories
ON
category.id = photographs.categories.id
ORDER BY
category.id DESC
";
$result = $this->pdo->prepare($query);
$result->execute();
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$post[] = $row;
}
$result = null;
$count = sizeof($post);
//get a list of the categories
for($i=0; $i < $count; $i++) {
$categories[$i] = $post[$i]['title'];
}
$categories = array_unique($categories);
//sort categories alphabetically
sort($categories);
//add the newest 20 photos to each category
$categories_count = count($categories);
$posts_count = count($post);
for($i=0; $i < $categories_count; $i++) {
$category_list[$i]['post_count'] = 0;
for($k=0; $k < $posts_count; $k++) {
if ($categories[$i] == $post[$k]['category_title']) {
if ($category_list[$i]['count'] == 19) {
break;
}
$category_list[$i]['category_title'] = $post[$k]['category_title'];
$category_list[$i]['post'][] = $post[$k];
$category_list[$i]['post_count']++;
}
}
}