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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭