Dorad Dorad - 6 months ago 268
PHP Question

MongoDB (php) - return document property as an array instead of multiple properties

I am reading a document from a mongodb database and passing it with php to client side.

The document contains an array property. The problem is that the client side receives it as an object with properties with the names

0
,
1
and so on, instead of a standard array.

This is the original data:

{
"_id" : ObjectId("573b47a1f99a8a1f9a6278a5"),
"persons" : [
{
"name" : "Moshe",
},
{
"name" : "E",
}, ...
]
}


As requested, I am attaching the var_export:

array (
0 =>
MongoDB\Model\BSONDocument::__set_state(array(
'_id' =>
MongoDB\BSON\ObjectID::__set_state(array(
)),
'persons' =>
MongoDB\Model\BSONArray::__set_state(array(
0 =>
MongoDB\Model\BSONDocument::__set_state(array(
'name' => 'Moshe',
)),
1 =>
MongoDB\Model\BSONDocument::__set_state(array(
'name' => 'E',
)),
)),
)),
)


And var_dump:

array(1) {
[0]=>
object(MongoDB\Model\BSONDocument)#40 (1) {
["storage":"ArrayObject":private]=>
array(2) {
["_id"]=>
object(MongoDB\BSON\ObjectID)#11 (1) {
["oid"]=>
string(24) "573b47a1f99a8d1f986278a5"
}
["persons"]=>
object(MongoDB\Model\BSONArray)#34 (1) {
["storage":"ArrayObject":private]=>
array(2) {
[0]=>
object(MongoDB\Model\BSONDocument)#10 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["name"]=>
string(5) "Moshe"
}
}
[1]=>
object(MongoDB\Model\BSONDocument)#12 (1) {
["storage":"ArrayObject":private]=>
array(1) {
["name"]=>
string(1) "E"
}
}
}
}
}
}
}


This is the PHP code(all of it):

function select(){
$conn = new MongoDB\Client("mongodb://localhost:27017");
$db = $conn->mydb;
$cursor = $db->entries_meta_data->find();
return current($cursor->toArray());
}


Then i pass the object to the client with a json_encode like this:

echo json_encode(select());


And the result as it appears in the client side is:

{
"_id" : ObjectId("573b47a1f99a8a1f9a6278a5"),
"persons" : {
"0" : {
"name" : "Moshe",
},
"1" : {
"name" : "E",
}, ...
}
}


EDIT:
LordNeo actually solve it. After reading his answer i have changed the last line in my "select" function to the following:

return json_decode(json_encode(current($cursor->toArray()),true);


It looks horrible, but it works.

I will be more than happy to hear a better solution.

Answer

When using json_decode you can use the optional "true" parameter and it will associate to an array

$obj = json_decode($json, true);
//$obj will be an associative array

php.net/manual/en/function.json-decode.php

Then you can strip off the index using array_shift:

$obj = array_shift($obj);

http://php.net/manual/en/function.array-shift.php

JSON adds the numeric index when it's not explicitly set, so you should probably send an array to the client instead of decoding -> removing index -> enconding -> removing index again.

Or just remove the index after being received by the client.

Comments