用户有订阅。它们存储在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排序))。
答案 0 :(得分:0)
$select = $db->prepare("select * from posts where owner_id = :owner_id order by id");
这样,记录将按升序排序,阅读ORDER BY子句。
答案 1 :(得分:0)
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'];
});
答案 2 :(得分:0)
如果您有一系列订阅,我建议您使用IN clausole。
\\