douxia2137
douxia2137
2016-04-25 17:58

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 doujianwan7570 5年前

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

    $roles = $collection->distinct('role', array("organization" => $curr_org['organization']);
    
    点赞 评论 复制链接分享