首页 > 解决方案 > PHP:在数组中选择表值?

问题描述

我有两个表:主题和用户。

这里的代码(不是我写的)选择 TOPICS 表值并将它们分配给一个数组:

$sql = 'SELECT forum_id, topic_id, topic_title, topic_time, topic_views, topic_poster, topic_posts_approved, topic_first_poster_name, topic_first_poster_colour, topic_last_post_id, topic_last_poster_name, topic_last_poster_colour, topic_last_post_time, topic_last_view_time, topic_last_poster_id
    FROM ' . TOPICS_TABLE . '
    WHERE ' . $this->db->sql_in_set('forum_id', $flast) . '
    AND ' . $this->content_visibility->get_visibility_sql('topic', 'topic') . '
    ORDER BY topic_last_post_time DESC';
$result = $this->db->sql_query_limit($sql, $this->config['last_total']);

while ($row = $this->db->sql_fetchrow($result))
{
$this->template->assign_block_vars('last_topic', array(
        'LAST_LINK'      => append_sid("{$this->phpbb_root_path}viewtopic.$this->phpEx", 'f=' . $row['forum_id'] . '&t=' . $row['topic_id']),
        'U_LAST_TOPIC'   => append_sid("{$this->phpbb_root_path}viewtopic.$this->phpEx", 'f=' . $row['forum_id'] . '&p=' . $row['topic_last_post_id'] . '#p' . $row['topic_last_post_id']),
        'LAST_POSTER'     => append_sid("{$this->phpbb_root_path}memberlist.$this->phpEx", 'mode=viewprofile' . '&u=' . $row['topic_poster']),
        'USERNAME_LAST'  => append_sid("{$this->phpbb_root_path}memberlist.$this->phpEx", 'mode=viewprofile' . '&u=' . $row['topic_last_poster_id']),
        'TOPIC_TITLE'                   => $row['topic_title'],
        'TOPIC_VIEWS'                   => $row['topic_views'],
        'TOPIC_REPLIES'                 => $row['topic_posts_approved'],
        'TOPIC_LAST_POSTER_NAME'        => $row['topic_last_poster_name'],
        'TOPIC_LAST_POSTER_COLOUR'      => $row['topic_last_poster_colour'],
        'TOPIC_LAST_POST_TIME'          => $this->user->format_date($row['topic_last_post_time']),
        'TOPIC_LAST_VIEW_TIME'          => $this->user->format_date($row['topic_last_view_time']),
        'USERNAME_AV'                   => "test",
    ));
}
$this->db->sql_freeresult($result);

数组中的最后一个元素是“USERNAME_AV”。我想为它分配来自 USERS 表的数据,其中表行/用户 id = topic_last_poster_id(取自 TOPICS 表),但不确定是否可以在数组内完成。

欢迎任何建议!

标签: phpmysqldatabase

解决方案


我将通过加入 users 表来实现这一点,以便您可以在 SQL 级别执行此操作。这提供了性能优势,因为您不需要建立多个数据库连接。您所要做的就是在您的选择上使用此语法JOIN USERS ON (USERS.id = TOPICS.topic_last_poster_id);

然后在您原来的选择中添加USER.USERNAME_AV as AV,您就可以像访问其他数据一样访问 AV。

就这样吧$row['av']

希望这有助于交配!干杯。


推荐阅读