用户已订阅。它们存储在PHP数组中。我正在尝试获取所有属于ID订阅的帖子,以显示在新闻Feed中。我试图让所有这些对象循环抛出该数组,然后按ID对它们进行排序。我想知道是否有更简单的方法,因为我决定使用“ LIMIT”以仅获取特定数量的帖子。
问题是,现在,我收到了所有帖子,而我只需要10个帖子。我正在使用PDO,MySQL,PHP。这是我现在拥有的代码:
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'];
});
现在,如果我限制为10个,则每个订阅将获得10个帖子,但摘要中需要10个帖子(最新的帖子(按ID排序))。
如果您有一系列订阅,我建议您使用IN Clausole。
$select = $db->prepare("select * from posts where owner_id IN(" .
implode(',',subscriptions_arr).") ORDER BY owner_id";
$result = $select->execute();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句