I have this error when I try to use my php file
Fatal error: Cannot use object of type MongoCursor as array in
Part of my code :
<?php
try {
$connection = new MongoClient();
$database = $connection->selectDB('test');
$collection = $database->selectCollection('articles');
} Catch(MongoException $e) {
die("Failed to connect to database ".$e->getMessage());
}
$cursor = $collection->find();
?>
<?php session_start();
?>
<html>
<p> test1 </p>
<p> test </p>
<h3> Comment the photo </h3>
<?php foreach($cursor['comments'] as $comment):
I think error is due to : - <?php foreach($cursor['comments'] as $comment):
or $cursor = $collection->find();
try this one it convert your mango cursor object to array($data).
then you can access data you want.
$data = array();
while($cursor->hasNext())
{
$cursor->next();
$temp = array();
$temp = $cursor->current();
array_push($data, $temp);
}
var_dump($data);
将$cursor
转换$cursor
Array:
$elements = $cursor->toArray();
Remove $cursor['comments']
and do a loop like this:
<?php
foreach ($cursor as $comment) {
?>
<p> <?php echo $comment['name']; ?> </p>
<?php
}
?>
Command:
$cursor = $collection->find();
gives you an array ( $cursor = $collection->findOne()
- gives you one element).
If you want to loop over comments then you have to use:
foreach($cursor as $oneElement) {
foreach($oneElement['comments'] as $comment) {
//some code
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.