简体   繁体   English

php mongodb array_unique在光标中不起作用

[英]php mongodb array_unique not working in cursor

I have the following code that produces a list of roles: 我有以下代码可产生角色列表:

// My original code (using find)
$cursor = $collection->find(array("organization" => $curr_org['organization'], "role" => array('$exists' => true)));

// The new code (using distinct)
$cursor = $collection->distinct('role', array("organization" => $curr_org['organization'], "role" => array('$exists' => true)));
foreach($cursor as $curr_org){
    echo '<ul>';
         echo '<li>';
              echo $curr_org['role'];
         echo '</li>';
    echo '</ul>';
}

The Data contained in $curr_org['role'] has duplicates in it. $ curr_org ['role']中包含的数据重复。

I've been messing around with array_unique and am unable to find the values of 'role'(getting array or NULL), or I'm getting the first and last values (id and organization). 我一直在弄乱array_unique并且无法找到'role'的值(获取数组或NULL),或者我正在获取第一个和最后一个值(id和组织)。

My example document is: 我的示例文档是:

{
    "_id" : ObjectId("571626ac768d884c268b456b"),
    "name" : "John Doe",
    "email" : "jack@daniels.com",
    "manager" : "Jack Daniels",
    "role" : "Boss Man",
    "password" : "$2y$10$Bk8kVZaa0K.AJ7GqWT65LuTkWYVtNw8jK6Am5izcnvHAVBIxj5VHC",
    "organization" : "MyOrg"
}

Can anyone let me know where I should add the array_unique in my loop so I only product a list of unique roles? 谁能让我知道我应该在循环中的array_unique位置添加array_unique ,这样我只产生一个唯一角色列表?

Best Regards, Dennis Hall 最好的问候,丹尼斯·霍尔

UPDATE: Using distinct seems to work, however, it only echo's the first character of each role as follows: 更新:使用distinct似乎可行,但是,它仅回显每个角色的第一个字符,如下所示:

Using Find: 使用查找:

Boss Man
Boss
Expeditor
Shift Manager
Ditch Digger
Boss
CEO
CEO
Expeditor

Using Distinct: 使用不同的:

B
B
E
S
D
C

SOLVED: The resolution was to use "distinct" in the cursor command. 已解决:解决方案是在光标命令中使用“ distinct”。 Also defining the key in the cursor command as well as in the loop caused the truncation of the results to a single letter. 在cursor命令以及循环中定义键也导致结果被截断为单个字母。 In the loop, the resolution was to remove the ['role'] from the echo $curr_org['role']; 在循环中,解决方案是从回显$ curr_org ['role']中删除['role']; line. 线。 The working code is as follows: 工作代码如下:

$cursor = $collection->distinct('role', array("organization" => $curr_org['organization'], "role" => array('$exists' => true)));
foreach($cursor as $curr_org){
    echo '<ul>';
         echo '<li>';
              echo $curr_org;
         echo '</li>';
    echo '</ul>';
}

如果您只关心角色,则可以使用MongoCollection::distinct

$roles = $collection->distinct('role', array("organization" => $curr_org['organization']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM