PHP + MySQL 新闻源的方法?

标签 php mysql arrays feed

我正在为我的应用程序开发新闻源,就像您在 Facebook 上使用的那样。所有新闻提要帖子都在同一个名为 newsfeed 的数据库表中。我的应用程序主要围绕用户和事件发展。 newsfeed 表有一个 newsfeed_type 列(int,1-14 指的是 newsfeed_types 表中的 id)。每个新闻源条目还有一个 other_idother_table + item_iditem_table。例如,用户向事件发布内容; user 是属于 users 表的 other_ideventitem_id属于 events 表。

理想情况下,我想收集大约 20 篇按时间戳降序排列的帖子,并在我的应用中使用“无限滚动”加载其余帖子。 PHP 我的脚本目前的工作方式是,它首先收集用户正在参加的每个事件以及该用户正在关注的所有用户/好友在单独 数组中。然后它使用 SQL 查询一个接一个地迭代这两个数组:

事件

$query = "select * from newsfeed where (other_id = ". $event["id"] ." and other_table = 'events') or (item_id = ". $event["id"] ." and item_table = 'events') order by date desc limit 10";

用户

$query = "select * from newsfeed where newsfeed_type != 5 and ((other_id = ". $user["id"] ." and other_table = 'users') or (item_id = ". $user["id"] ." and item_table = 'users')) order by date desc limit 10";

我编写脚本时没有意识到它要求为每个事件和用户输入 10 个条目。让它请求 1 个条目也不是很理想,因为用户可以关注无限数量的事件,而用户每个项目只有一个新闻提要帖子。

你认为最好的做法是让它只获取 newsfeed 表中的 20 个最新条目,而不必迭代两个数组来获取获取新闻源所需的数据一次输入一个?我想我可以在一个字符串中收集 idtable 并使 SQL 查询一次性获取所有内容,而不是在循环或其他东西中,但我想我'如果有人处理过这个问题并想出了一个天才的解决方案,我会问问你们。

最佳答案

我找到了解决方案。我没有抓取每个用户类型并将它们存储在单独的数组中以遍历它们,而是分别 foreach 了两个数组并制作了一个字符串用作 sql 查询,限制为 25 个项目。

$sql_string = "";

foreach ($events as $event) {

    $sql_snippet = "(other_id = ". $event["id"] ." and other_table = 'events') or (item_id = ". $event["id"] ." and item_table = 'events')";

    if ($is_adding == "true") {
        $last_id = $_POST["last_id"];
        $sql_snippet .= " and id < $last_id";
    }

    if ($sql_string == "") {
        $sql_string = "(". $sql_snippet .") ";
    } else {
        $sql_string .= "or (". $sql_snippet .") ";
    }
}

foreach ($users as $user) {

    $sql_snippet = "(other_id = ". $user["id"] ." and other_table = 'users') or (item_id = ". $user["id"] ." and item_table = 'users')";

    if ($is_adding == "true") {
        $last_id = $_POST["last_id"];
        $sql_snippet .= " and id < $last_id";
    }

    if ($sql_string == "") {
        $sql_string = "(". $sql_snippet .") ";
    } else {
        $sql_string .= "or (". $sql_snippet .") ";
    }
}

$query = "select * from newsfeed where newsfeed_type = 12 or ($sql_string) order by date desc limit 25";

关于PHP + MySQL 新闻源的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43905468/

相关文章:

PHP/MySQL 按日期和随机排序

arrays - Swift 中带有数组的 For-In 循环中迭代器元素的可变性

php - 存储大量内容的建议方法是什么?

mysql - 从另一个表的另一个字段中选择表中的字段

php - 在 php 和 MySQL 中处理数字列表

c# - MySql Entity Framework 自动增量错误

C# 如何将数组中的每个元素添加到 XML 树中的子节点?

java - HashMap 到数组 : throws java. lang.ArrayStoreException

php - 简单的 HTML Dom : check if tag exist

php - Mysql查询没有插入值