dongxie548548 2016-02-28 02:45
浏览 84

使用php从mongodb中检索的数据中显示特定的“键值”对

This is the php code.

<?php 
// connect to mongodb
$m = new MongoClient();

// select a database
$db = $m->Example;

$collection="User";
$Query = array("Username"=>$username);
$j = $db->$collection->find($Query);   

foreach ($j as $k) {
   echo"<pre>";var_dump($k); echo"</pre>";
}

 foreach($j as $k => $v) {

       echo $k.'='.$j[$k].'<br>';

}
?>

In this, the data is retrieved in $j variable an when var_dump($k) is used the output is as follows:

array(8) {
  ["_id"]=>
  object(MongoId)#6 (1) {
  ["$id"]=>
  string(24) "56d1cb49097ed3241d000029"
  }
  ["Fname"]=>
  string(4) "Ritu"
  ["Lname"]=>
  string(3) "Rad"
  ["Username"]=>
  string(4) "riri"
  ["Password"]=>
  string(4) "riri"
  ["Email"]=>
  string(23) "ritikatra@gmail.com"
}

But if you try to display individual key value pair as in the next foreach loop you get the following error:

Fatal error: Cannot use object of type MongoCursor as array

How to display only a particular key and it's value? eg: Email ritikatra@gmail.com

  • 写回答

1条回答 默认 最新

  • dongzilu0178 2016-02-28 16:42
    关注

    Result of \MongoCollection::find() (your $j) variable is an instance of \MongoCursor class which implements \Iterator - it allows you to loop over it but it doesn't have keys (i.e. doesn't implement \ArrayAccess). If you want to use your results as an array you should call

    $array = iterator_to_array($j);
    

    Now you can use $array as it'd be plain array:

    echo $array[0]['Email']
    
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路