我在使用 PHP 时遇到了一个非常有趣的问题。以下代码从文本文件中获取一行,将该文本作为 json 解码为 stdClass 对象,然后根据其属性之一有条件地将其放入数组中。
$fileStream = @fopen($fileName, 'r+');
$lastUpdate = $_POST['lastUpdate'];
if($fileStream) {
$eventArray = array();
while (($buffer = fgets($fileStream, 8192)) !== false) {
$decodedEvent = json_decode($buffer);
echo var_dump($decodedEvent);
if ($decodedEvent->timestamp > $lastUpdate) {
array_push($eventArray, $decodedEvent);
}
}
$jsonEvents = json_encode($eventArray);
echo $jsonEvents;
}
else {
$fileStream = @fopen($fileName, 'a');
}
@fclose($fileStream);
这会产生错误:
Notice:Trying to get property of non-object in C:\****\gameManager.php on line 23
我知道该对象以多种方式有效。例如, var_dump 正在生成:
object(stdClass)#1 (3) {
["name"]=>
string(4) "move"
["args"]=>
array(3) {
[0]=>
int(24)
[1]=>
int(300)
[2]=>
int(50)
}
["timestamp"]=>
float(1352223678463)
}
如果我尝试使用 $decodedEvent 访问,则会$decodedEvent["timestamp"]
收到一条错误消息,告诉我对象不能作为数组访问。
此外,它确实回显了正确的 json,它只能从正确的对象编码:
[{"name":"move","args":[24,300,50],"timestamp":1352223678463}]
我在这里遗漏了什么,还是 PHP 行为不端?任何帮助是极大的赞赏。
编辑:这是来自文件的输入:
{"name":"move","args":[24,300,50],"timestamp":1352223678463}