0

我的 mongodb 数据库中有一个用户列表,然后可以相互遵循 - 非常标准。使用 php 我想检查特定用户是否正在关注另一个用户。我的数据看起来像这样。

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',
        ),
      ),
    )

我想要一个查询来检查 Joe 是否在关注 Sam(他不是) - 所以它不会产生任何结果。但是,如果我要查询数据库以检查 Tom 是否在关注 Sam,那么它会产生一个结果表明他是(因为他是)。你知道我会如何在 PHP 中做到这一点吗?我已经尝试过 Foreach 循环,但我无法得到我想要的结果。

4

2 回答 2

0

通过数据库查询,通过 php 它会占用更多资源
如果你想通过 php 你可以这样做

$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;
于 2015-12-19T22:07:17.857 回答
0

此类查询最好在 SQL 中完成,但如果您坚持使用基于 PHP 的解决方案,我建议将数据结构转换为按名称键入的项目。一旦你有了它,找到关系就是小菜一碟:

function organisePersons($data) {
    $persons = array();
    foreach($data as $person) {
        $list = array();
        foreach($person["following"] as $following) {
            $list[$following["username"]] = $following["username"];
        }
        $person["following"] = $list;
        $person["followedBy"] = array();
        $persons[$person["username"]] = $person;
    }
    // link back to get all "followedBy":
    // You can skip this block if you don't need "followedBy":
    foreach ($persons as $person) {
        foreach($person["following"] as $following) {
            echo $person["username"] . " f. $following<br>";
            if (!isset($persons[$following])) {
                $persons[$following] = array(
                    "_id" => null, // unknown
                    "username" => $following,
                    "following" => array(),
                    "followedBy" => array()
                );
            }
            $persons[$following]["followedBy"][] = $person["username"];
        }
    }
    // return the new structure
    return $persons;
}

因此,首先使用您拥有的数据调用上面的函数:

$persons = organisePersons($data);

然后你可以这样写:

if (isset($persons["Joe"]["following"]["Sam"])) {
    echo "Joe is following Sam";  // not in output
};
if (isset($persons["Tom"]["following"]["Sam"])) {
    echo "Tom is following Sam";  // in output
};

但是也:

echo "Tom is following " . implode($persons["Tom"]["following"], ", ");
// Output: Tom is following Joe, John, Sam

甚至是相反的问题“汤姆后面跟着谁?”:

echo "Tom is followed by " . implode($persons["Tom"]["followedBy"], ", ");
// Output: Tom is followed by Joe
于 2015-12-19T23:11:57.163 回答