duanmo6937 2015-12-19 21:51
浏览 48

使用PHP搜索数组中的值

I have a list of users in my mongodb database, which can then follow each other -pretty standard. Using php I want to check if a specific user is following another user. My data looks like this.

array (
  '_id' => ObjectId("56759157e1095db549d63af1"),
  'username' => 'Joe',
  'following' => 
  array (
    0 => 
    array (
      'username' => 'John',
    ),
    1 => 
    array (
      'username' => 'Tom',
    ),
  ),
)
array (
      '_id' => ObjectId("56759132e1095de042d63af4"),
      'username' => 'Tom',
      'following' => 
      array (
        0 => 
        array (
          'username' => 'Joe',
        ),
        1 => 
        array (
          'username' => 'John',
        ),
        2 => 
        array (
          'username' => 'Sam',
        ),
      ),
    )

I want a query that will check if Joe is following Sam (which he's not) - so it would produce no results. However, if I was to query the database to check if Tom was following Sam, then it would produce a result to indicate he is (because he is). Do you know how I would do this in PHP? I've experimented with Foreach loops, but I haven't been able to get the results I want.

  • 写回答

2条回答 默认 最新

  • duanhuantong8278 2015-12-19 22:07
    关注

    Make it by DB query, by php it will take more resources
    Still if you want by php you can make it so

    $following=false;
    foreach($data as $v) if ($v['username'] == 'Joe') {
        foreach($v['following'] as $v1) if (in_array('Sam', $v1)) {
            $following=true;
            break 2;
        }
    }
    echo $following;
    
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源