PHP排序是唯一的


PHP sort unique

我对PHP完全陌生,需要检索所有值​哪一个​CONTAIN城市。但是,这会为每个城市返回多个文档。如何只显示一次而不显示多次城市?

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

<?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>

这应该可以完成

//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
});