0

我正在制作一个可以同时运行多个房间的游戏。我有一个 MySQL 表“房间”来保存所有房间的信息。

此表中的字段包括“id”,房间的数字 id,以及“user1”到“user6”,房间中用户的数字 id。

在一页上,我必须对所有房间的这些信息做一些事情,我当前的代码是这样的:

//query() is just a function which implements mysqli::query with logging,
//  error handling, etc. It uses the same connection on each call so
//  there is no overhead of opening a new connection.
$q = query("SELECT id,some_other_fields,user1,user2,user3,...,user6 FROM rooms");
while($r = $q->fetch_assoc()){
    //some stuff here

    foreach(array($r['user1'],$r['user2'],...,$r['user6']) as $user)
        stuff((int)$user);

    //some more stuff
}

如您所见,我必须为用户显式创建一个数组并循环遍历它。
有更好的方法吗?

我正在考虑这段代码:

$q = query("SELECT id,some_other_fields FROM rooms");
while($r = $q->fetch_assoc()){
    //some stuff here

    foreach(query("SELECT user1,user2,user3,...,user6 FROM rooms WHERE id=".$r['id'])->fetch_assoc() as $user)
        stuff((int)$user);

    //some more stuff
}

如果房间数量通常在 10~20 间左右,这样是否合适?

4

1 回答 1

1

在执行查询之前创建一个字段数组,如下所示

$fields = array('user1','user2','user3','user4');

$q = query("SELECT id,some_other_fields, ". implode($fields, ',') ." FROM rooms");
while($r = $q->fetch_assoc()){
    //some stuff here

    foreach($fields as $field)
        stuff((int)$r[$field]);

    //some more stuff
}

然后你可以改变你的查询和你的循环,而只改变一行代码。

于 2013-02-17T03:53:08.500 回答