i want to display comments with php. My database is mongodb, and this is my collection articles :
{ "_id" : ObjectId("55be4a1a71dd7ecc05b7acd9"), "title" : "test", "content" : "test", "user" : "Paul", "saved_at" : ISODate("2015-08-02T16:49:30.480Z"), "comments" : [ { "comment" : "this is my test", "user" : "Paul" } ], { "comment" : "my second test", "user" : "Paul" } ] }
So i want display this comments : "this is my test" and "my second test" i have this code but it don't work :
<?php
try {
$mongodb = new MongoClient();
$collection = $mongodb->blog->articles;
} catch (MongoConnectionException $e) {
die('Failed to connect to MongoDB '.$e->getMessage());
}
$query=array();
$cursor=$collection->find($query);
foreach($cursor as $doc){
echo $doc['comments'];
}
?>
so when i use this code i have this error :
Array to string conversion in line 86, its this line
echo $doc['comments'];
thanks with the help
It's exactly as the error says - you're trying to print out an array, and echo
can print only scalars (int, string, float, etc).
To just quickly display the array, you could use var_dump()
, but this should not be used in production. Instead, you could iterate over the comments like this:
foreach($cursor as $doc)
{
foreach($docs['comments'] as $comment)
{
echo '"' . $comment['comment'] .'" by ' . $comment['user'];
}
}