Last active
July 26, 2018 13:31
-
-
Save domainoverflow/2139be1a9bf834e92e8d497811809044 to your computer and use it in GitHub Desktop.
Convert MongoDB cursor to PHP Array at a lower cost. Instead of using cursor.toArray() (at the time of the query ) which can be heavy, the function below allows you to convert MongoDB\Cursor directly into a PHP Array locally, improving the overall performance of the Iteration between PHP and MongoDB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public function convertMongoDBCursorToArray($dbcursor) { | |
$counter=0; $x=0; | |
$finalarray = Array() ; $convertedarray=Array() ; | |
foreach($dbcursor as $document) { $finalarray[$counter]=$document; $counter++;} | |
$finalarray=array_values($finalarray); | |
$thissize = count($finalarray); | |
$counter=0; | |
for($x=0;$x<$thissize;$x++) { | |
$fields = array_keys((array)$finalarray[$x]); $values = array_values((array)$finalarray[$x]); | |
$fieldscount = count($fields); | |
$fields = array_values($fields); | |
for($y=0;$y<$fieldscount;$y++) { | |
$fieldname = $fields[$y]; | |
$value = $values[$y]; | |
$convertedarray[$x][$fieldname] =$value; } // y inner | |
} // x outter | |
return $convertedarray; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment