conversion of veriable to array type in php

20 views
Skip to first unread message

Omkar Kulkarni

unread,
Sep 25, 2016, 9:26:04 AM9/25/16
to mongodb-user
im trying to store collections in a variable using  "find()" in php
but i dont know in which data type it stores collection in variable
now i waned to use it as array
so how can i use it as array
pleas help !!!!

Wan Bachtiar

unread,
Sep 25, 2016, 11:57:58 PM9/25/16
to mongodb-user

now i waned to use it as array so how can i use it as array

Hi Omkar,

Assuming you’re using MongoDB PHP Library, the find() method returns a MongoDB\Driver\Cursor object which you could iterate to access all matched documents. For example:

$collection = (new MongoDB\Client)->databaseName->collectionName;
$cursor = $collection->find(['field' => 'value_to_search']);
foreach ($cursor as $document) {
    var_dump($document);
}

Depending on what you’re trying to achieve, you could also store the result into a PHP array if you prefer, an example:

$array_stack = array();
$cursor = $collection->find(['field' => 'value_to_search']);
foreach ($cursor as $document) {
    // push to our array variable.
    array_push($array_stack, $document);
}
print_r($array_stack);

I would recommend to check out MongoDB PHP Library CRUD tutorial. There are good examples and guides to help you be familiar with MongoDB operations via PHP. See also MongoDB for the PHP mind part 1.

If you have further questions, please provide:

  • MongoDB PHP Library version.
  • Your PHP code snippet.
  • Examples of your MongoDB documents.
  • Examples of what you’re trying to do to clarify your case.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages