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;
    
    评论

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?