使用PHP搜索数组中的值

时间:2015-12-19 21:51:31

标签: php mongodb multidimensional-array embedded-documents

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

x = (int*)realloc(x, sizeof(int)*(int)temp);

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

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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