dongqixuan3112 2011-12-15 00:36
浏览 20

在php数组中搜索元素

I've got

  • a users table named "members"
  • a rooms table named "rooms"
  • a table that associates the user id to the ids of the rooms "membersRooms"

I should write a loop that prints a dropdown for each user with all the rooms, but that adds the attribute "selected" to rooms associated with the user

What's wrong with this loop?

$members = mysql_query("SELECT * FROM members ");
$rooms = mysql_query("SELECT * FROM rooms");

while($member = mysql_fetch_array($members)){ 
    echo("<select>");
    $roomsOfUser = mysql_query("SELECT roomID FROM membersRooms WHERE userID=".$member["id"]);
    $cuArray = mysql_fetch_array($roomsOfUser); 

    while($room = mysql_fetch_array($rooms)){
        if(in_array($room["id"],$cuArray,true))
            echo("<option selected='selected'>".$room["roomName"]."</option>");
        else
            echo("<option>".$class["roomName"]."</option>");
    }
    echo("</select>");
}
  • 写回答

3条回答 默认 最新

  • duanao4503 2011-12-15 01:34
    关注

    To make this a little easier on you, you could try utilizing left and right joins on your database. This would significantly reduce your server load and still allow you to do the same functionality.

    I believe, if I'm reading your database structure right, that you'ld want something along the lines of:

     SELECT members.id as memberID, rooms.id as roomID, rooms.roomName, membersRooms.roomID as memberRoom
     FROM members
     LEFT JOIN membersRooms
     ON members.id = membersRooms.userID
     RIGHT JOIN rooms
     ON membersRooms.roomID = rooms.id
    

    Then in PHP you should be able to just keep track of when your memberID changes, and when it does, start a new select. If I didn't totally bungle that SQL (which I might have) then the resulting rows should look something like:

    memberID    |   roomID  |  roomName  |  memberRoom
        1             1          foo             1
        1             2          bar             1
        2             1          foo             1
        2             2          bar             1
    

    So on your loop iteration you would use roomID and roomName to build your select, and if RoomID matched memberRoom then you would select that row.

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看