首页 文章

无法从有效的stdClass对象获取属性

提问于
浏览
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["timestamp"] 访问$ decodingEvent我收到一个错误,告诉我对象不能作为数组访问 .

此外,它确实回显了正确的json,它只能从适当的对象编码:

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

我在这里遗漏了什么,还是PHP行为不端?任何帮助是极大的赞赏 .

EDIT :这是文件的输入:

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

2 回答

  • 1

    您可以尝试此函数将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;
            }
        }
    

    Sources

  • 0

    您的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)
    

    另请注意,这是一个通知 . 虽然我提倡干净的代码,严格来说并不是错误 .

相关问题