douxia2137 2016-04-25 17:58
浏览 33
已采纳

php mongodb array_unique无法在游标中工作

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.

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).

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?

Best Regards, Dennis Hall

UPDATE: Using distinct seems to work, however, it only echo's the first character of each role as follows:

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. Also defining the key in the cursor command as well as in the loop caused the truncation of the results to a single letter. In the loop, the resolution was to remove the ['role'] from the echo $curr_org['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>';
}
  • 写回答

1条回答 默认 最新

  • doujianwan7570 2016-04-25 18:11
    关注

    If all you care about are roles you could use MongoCollection::distinct

    $roles = $collection->distinct('role', array("organization" => $curr_org['organization']);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?