PHP排序独特

时间:2015-02-23 17:29:07

标签: php mongodb

我是PHP新手,我需要检索所有含有城市的值。但是,这会为每个城市返回多个文档。我如何只展示一次城市而不是多次?

所有项目包括城市包括几个项目包含相同的城市,希望在我的下拉列表显示唯一的城市。现在在上面的代码中显示所有城市都是。

<?php
$connection = new MongoClient( "" ); // connect to a remote host at a given port
$collection = $connection->value1->value2;
?>

<select name="City" class="form-control">
         <option value="0">Please Select</option>

    <?php $cursor = $collection->find()->sort( array( 'City' => 1 ) );

    foreach ($cursor as $document) {

        echo "<option value='" . $document["City"] . "'>" . $document["City"]                        . "</option>";

    }
    ?>

 </select>

1 个答案:

答案 0 :(得分:1)

这应该可以解决问题

//we will use several temporary values to remove the duplicate City's, values that will be of no use after we're done. thus i want to make a new scope for this.
//php scoping rules suck, and to create a new scope, we need to create a function, iirc.
call_user_func(function() use( &$cursor) { //declare and call a nameless function, and copy $cursor to this function's scope. 
$a1 = array();
$unsetarr = array();
foreach($cursor as $key => $document) {//iterate $cursor
    if (in_array($document["City"], $a1)) { 
    //if we have seen this city before, mark this $cursor entry for deletion. 
    //(we won't delete it right away because modifying the length of the array WHILE iterating it sounds like a bad idea. it certainly would be a bad idea in certain other languages. maybe PHP could handle it, but i don't know.)
        $unsetarr[] = $key;
    }
    $a1[] = $document["City"];
}
foreach($unsetarr as $tounset) {
    //delete all entries that was marked for deletion in the previous loop.
        unset($cursor[$tounset]);
    }
    //maybe $cursor=array_values($cursor); to fix the keys
});