如何获得"任何"来自对象的mongodb结果键

时间:2016-08-04 10:43:18

标签: php mongodb mongodb-query

我有一个返回CSV格式结果的PHP脚本:

# cat query.php
<?php

include '../misc.php';
$values=$_GET?$_GET:$_POST;

{
  $ts = isset($values['t'])?strtotime($values['t']):strtotime("-1 hour");
  $result=Query('iot.data',['key' => $values['key'], 'timestamp' => array('$gte' => $ts)],['projection' => array('_id' => 0, 'timestamp' => 1, $values['col'] => 1), 'sort' => array('timestamp' => 1)]);

    if ($values['col'] == 'temp1') echo "Timestamp, Temperature\n";
    if ($values['col'] == 'BusV2') echo "Timestamp, Battery V\n";
    if ($values['col'] == 'uv1') echo "Timestamp, UV\n";


  foreach ($result as $r) { 
    $d = date('c',$r->timestamp);
    if (isset($r->temp1)) echo "$d, $r->temp1\n";
    if (isset($r->BusV2)) echo "$d, $r->BusV2\n";
    if (isset($r->uv1)) echo "$d, $r->uv1\n";
  };
};

使用&#34; col&#34;参数我可以决定带有时间戳的返回键。

如果没有foreach循环中的IF,我怎样才能获得理想的结果?

我将如何编码:

foreach ($result as $r) { 
    $d = date('c',$r->timestamp); 
    echo "$d, $r->$values['col']\n" // where object $r key comes from variable 'col'
}

如果我将该foreach更改为: foreach ($result as $r => $v) {

因为$v没有得到密钥$r的值,$v现在是$r之前的...

print_r($v);

的结果
stdClass Object
(
    [temp1] => 25.2
    [timestamp] => 1470304854
)

1 个答案:

答案 0 :(得分:1)

如果我理解你想要实现的目标,你可以使用:

foreach ($result as $r) { 
    $d = date('c',$r->timestamp);    
    echo "$d, " . $r->{$values['col']} . "\n";
};

您的mongo似乎正在返回stdClass Object,您可以使用->进行访问,这就是$r[$values['col']]发出500错误的原因。