如何在php中从mongodb集合中获取所有记录
我尝试了以下代码来选择mongodb集合中的所有记录,但只会出现最后一条插入的记录如何在php中从mongodb集合中获取所有记录,php,mongodb,Php,Mongodb,我尝试了以下代码来选择mongodb集合中的所有记录,但只会出现最后一条插入的记录 <?php $m=new MongoClient(); $db=$m->trip; if($_SERVER['REQUEST_METHOD']=="POST") { $userId=$_POST['userId']; $param=explode(",",$userId); $collection=$db->chat; $record=$collection-&
<?php
$m=new MongoClient();
$db=$m->trip;
if($_SERVER['REQUEST_METHOD']=="POST")
{
$userId=$_POST['userId'];
$param=explode(",",$userId);
$collection=$db->chat;
$record=$collection->find(array("userId"=>$userId));
if($record)
{
foreach($record as $rec)
{
$json=array("msg"=>$rec);
}
}
else
{
$json=array("msg"=>"No Records");
}
}
else
{
$json=array("msg"=>"Request Method is Not Accespted");
}
//output header
header('Content-type:application/json');
echo json_encode($json);
但只有一张唱片会出现
请帮助我您的问题是每次执行foreach
时,它都会覆盖$json
变量的内容。尝试先声明$json
,然后使用它
if($record)
{
$json = array();
foreach($record as $rec)
{
$json[] = array("msg"=>$rec);
// /\ this means adding the attribution to the end of the array.
}
}
这样,每次执行foreach
时,$json
的内容不会被替换,而是被追加。您的问题是,每次执行foreach
时,它都会覆盖$json
变量的内容。尝试先声明$json
,然后使用它
if($record)
{
$json = array();
foreach($record as $rec)
{
$json[] = array("msg"=>$rec);
// /\ this means adding the attribution to the end of the array.
}
}
这样,每次执行foreach
时,$json
的内容不会被替换,而是会被追加。它的工作原理。谢谢它的工作原理。谢谢