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 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型