我有一个返回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";
};
};
使用“col”参数,我可以决定使用时间戳返回哪个键.
如果没有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
)
最佳答案 如果我理解你想要实现的目标,你会使用:
foreach ($result as $r) {
$d = date('c',$r->timestamp);
echo "$d, " . $r->{$values['col']} . "\n";
};
看来你的mongo正在返回一个stdClass对象,你可以使用 – >来访问它,这就是$r [$values [‘col’]]给出500错误的原因.