0

我在使用 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}
4

2 回答 2

1

您的 JSON 格式不正确。这并不是说无效。但是给定这种格式,根元素是一个stdClass.

array(1) {
  [0] =>
  class stdClass#1 (3) {
     // ...

如果这是一个真正的单个对象,我将在源头使用以下正确的 JSON 解决此问题:

{"name":"move","args":[24,300,50],"timestamp":1352223678463}

如果这不可能,您需要在 PHP 中使用正确的数组表示法访问它:

echo $decodedEvent[0]->timestamp;

更新

根据您的代码,您提供的更新后的 JSON 似乎有效且格式正确。我的猜测是文件中的一行不包含有效的 JSON(例如空行),因此json_decode()失败导致 PHP 通知。

我鼓励您在循环中对此进行测试:

if ($decodedEvent && $decodedEvent->timestamp > $lastUpdate)

还要记住这是一个通知。虽然我提倡干净的代码,但严格来说这不是一个错误。

于 2012-11-06T18:30:43.237 回答
0

您可以尝试使用此函数将 stdClass 对象转换为多维数组

    function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    } 

来源

于 2012-11-06T18:29:52.833 回答