douwei1950 2015-05-29 12:17 采纳率: 0%
浏览 25

从MySql Query获取信息并将其放入PHP数组中

I have a table of which I must select information using a MySQLi Query and push it to the end of a PHP array.

The table is in this format:

table = friends

id  user1  user1_id  user2  user2_id  datemade              accepted
1   name1  1         name2  2         2015-05-27 03:24:32   1
2   name3  3         name2  2         2015-05-27 03:24:32   1
3   name3  3         name1  1         2015-05-27 03:24:32   1
4   name4  4         name2  2         2015-05-27 03:24:32   1
  • id = an auto_incrementing number to keep track of everything
  • user1 = the person's name that asks for friendship
  • user1_id = that person's special unique id
  • user2 = name of the person that accepts/decline's friendship
  • user2_id = that person's special unique id
  • datemade = the date it was made :P
  • accepted = did he accept? (don't worry about this)

I want to select all users that are friends with $u. In this example, $u's id is 1 (name is name1). After running the query it would push it to the end of friend_array.

So if I printed this array the output would be:

2, 3

Since, id=1 is friends with id=2 and id=3

What query should I do and how would I push that to an array (I know about about array_push but I do not know how to implement it)?

  • 写回答

2条回答 默认 最新

  • dongxi3911 2015-05-29 13:17
    关注

    Please try this code. It will return the array for all user's friends.

    $sql = "SELECT user1 AS user FROM friends UNION SELECT user2 AS user FROM friends";
    
    $data = mysqli_query($sql);
    
    while ($v = mysqli_fetch_assoc($data)) {
    $sql = mysqli_query("SELECT * FROM `friends` where (user1 = '" . $v['user'] . "' or user2 = '" . $v['user'] . "')");
    $arr = array();
    while ($array = mysqli_fetch_assoc($sql)) {
    
        if ($array['user1'] == $v['user']) {
            $arr[$v['user']][] = $array['user2_id'];
        } else {
            $arr[$v['user']][] = $array['user1_id'];
        }
      }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口