json对象在变量$中作为输出结果如
Array ( [ts] => MongoTimestamp Object ( [sec] => 1497334764 [inc] => 1 ) [t] => MongoInt64 Object ( [value] => 1 ) [h] => MongoInt64 Object ( [value] => -3885623284897060533 ) [v] => 2 [op] => i [ns] => mgl.triggersTbl [o] => Array ( [_id] => MongoId Object ( [$id] => 593f83ec1d7859cc0f000029 ) [Name] => Ahmad [Address] => Delhi ) )
Array ( [ts] => MongoTimestamp Object ( [sec] => 1497349628 [inc] => 1 ) [t] => MongoInt64 Object ( [value] => 8 ) [h] => MongoInt64 Object ( [value] => -3083419979530819825 ) [v] => 2 [op] => i [ns] => mgl.triggersTbl [o] => Array ( [_id] => MongoId Object ( [$id] => 593fbdfc1d78591819000029 ) [Name] => Nehal [Address] => Mumbai ) )
Array ( [ts] => MongoTimestamp Object ( [sec] => 1497428148 [inc] => 1 ) [t] => MongoInt64 Object ( [value] => 9 ) [h] => MongoInt64 Object ( [value] => -660915868390613413 ) [v] => 2 [op] => i [ns] => mgl.triggersTbl [o] => Array ( [_id] => MongoId Object ( [$id] => 5940f0b41d78591414000029 ) [Name] => Seema [Address] => Mumbai ) )
代码是
$cursor = $c->find(array('ns'=> 'mgl.triggersTbl', 'op' => 'i'));
// $cursor->timeout(-1);
$cursor->tailable(true);
//$cursor->awaitData(true);
while ($cursor->hasNext()) {
$cursor->timeout(-1);
try
{
$results =array();
$results = $cursor->getNext();
var_dump($results);
}
现在我试图逐个获取这些值,以使其显示。
foreach ($results as $key)
{
foreach ($key as $p => $res)
{
echo "Timestamp"." : ". $key["sec"]."<br/>";
echo "Name"." :".$res["Name"]."<br/>";
echo "Address"." :".$res["Address"];
}
}
此代码不起作用。它抛出错误信息。
“不能在”echo“Timestamp”。“中使用MongoTimestamp类型的对象作为数组。”:“。 $键[ “秒”] “
”;“
如果我使用
foreach ($results as $res)
{
echo "Name"." :".$res["Name"]."<br/>";
echo "Address"." :".$res["Address"];
}
仍然会抛出错误消息
请帮助!!!
答案 0 :(得分:1)
数组中的每个元素都是不同的,因此循环遍历数组中的每个元素是没有意义的。
假设以下是$results
,
array(7) {
["ts"]=> object(MongoTimestamp)#6 (2) {
["sec"]=> int(1497334764)
["inc"]=> int(1)
}
["t"]=> object(MongoInt64)#7 (1) {
["value"]=> string(1) "1"
}
["h"]=> object(MongoInt64)#8 (1) {
["value"]=> string(20) "-3885623284897060533"
}
["v"]=> int(2)
["op"]=> string(1) "i"
["ns"]=> string(15) "mgl.triggersTbl"
["o"]=> array(3) {
["_id"]=> object(MongoId)#9 (1) {
["$id"]=> string(24) "593f83ec1d7859cc0f000029"
}
["Name"]=> string(5) "Ahmad"
["Address"]=> string(5) "Delhi"
}
}
您可以使用以下代码从上到下打印所有值。
echo $results["ts"]->sec;
echo $results["ts"]->inc;
echo $results["t"]->value;
echo $results["h"]->value;
echo $results["v"];
echo $results["op"];
echo $results["o"]["_id"]->{'$id'};
echo $results["o"]["Name"];
echo $results["o"]["Address"];
答案 1 :(得分:0)
如果您对此表单中的数组使用foreach
,则会遍历值,而不是键。第一个值是您的对象(MongoTimestamp),您可以在第一个echo
中作为数组访问它。请参阅评论以获取其他建议。
更新:数组有点难以阅读,可能需要print_r(array_keys($result))
来确保结构符合您的预期(而不是嵌套在某个级别)更深入的数组中的数组)。