A user has subscriptions. They are stored in PHP array. I am trying to get all of the posts that belong to subscriptions ordered by id to display in the news feed. I was trying to get all of them looping throw the array, and after that sorting them by ID. I am wondering if there is an easier way for that, as I decided to use the 'LIMIT' in order to get only the specific amount of posts.
The problem is that now, I get all of the posts, and I need only 10 (for example). I am using PDO, MySQL, PHP. Here is the code I have now:
foreach(subscriptions_arr as $sub) {
$select = $db->prepare("select * from posts where owner_id = :owner_id");
$select->bindParam(':owner_id', $sub);
$select->execute();
$posts = $select->fetchAll(PDO::FETCH_ASSOC);
// pushes all of the posts into one multi-array with only 2 levels
// (instead of 3 as before)
// to be able to sort it by id, and not by subscriptions
foreach ($posts as $post) {
$new_array[] = $post;
}
}
// sorts by id
usort($new_arr, function($a, $b) {
return $b['id'] - $a['id'];
});
Now, if I will limit to 10, I will get 10 posts for each of subscriptions, but I need 10 in summary (the latest ones (ordered by ID)).
$select = $db->prepare("select * from posts where owner_id = :owner_id order by id");
这样,记录将以升序排序,请阅读有关ORDER BY子句的信息。
foreach(subscriptions_arr as $sub) {
$select = $db->prepare("select * from posts order by ID DESC group by owner_id LIMIT 10");
$select->execute();
$posts = $select->fetchAll(PDO::FETCH_ASSOC);
// pushes all of the posts into one multi-array with only 2 levels
// (instead of 3 as before)
// to be able to sort it by id, and not by subscriptions
foreach ($posts as $post) {
$new_array[] = $post;
}
}
// sorts by id
usort($new_arr, function($a, $b) {
return $b['id'] - $a['id'];
});
If you have an array of subscriptions i can suggest to use IN clausole.
$select = $db->prepare("select * from posts where owner_id IN(" .
implode(',',subscriptions_arr).") ORDER BY owner_id";
$result = $select->execute();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.