Php Can';无法从有效的stdClass对象获取属性
我对PHP有一个非常有趣的问题。下面的代码从一个文本文件中获取一行,将该文本作为json解码到一个stdClass对象中,然后将其有条件地放在一个数组中的一个属性上Php Can';无法从有效的stdClass对象获取属性,php,json,stdclass,Php,Json,Stdclass,我对PHP有一个非常有趣的问题。下面的代码从一个文本文件中获取一行,将该文本作为json解码到一个stdClass对象中,然后将其有条件地放在一个数组中的一个属性上 $fileStream = @fopen($fileName, 'r+'); $lastUpdate = $_POST['lastUpdate']; if($fileStream) { $eventArray = array(); while (($buffer = fgets($fi
$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”]
访问$decodedEvent,我会收到一个错误,告诉我对象不能作为数组访问
此外,它确实回显了正确的json,这只能从正确的对象进行编码:
[{"name":"move","args":[24,300,50],"timestamp":1352223678463}]
我在这里遗漏了什么,还是PHP行为不端?非常感谢您的帮助
编辑:以下是来自文件的输入:
{"name":"move","args":[24,300,50],"timestamp":1352223678463}
您可以尝试使用此函数将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;
}
}
您的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\u decode()
失败,导致PHP通知
我鼓励您在循环中对此进行测试:
if ($decodedEvent && $decodedEvent->timestamp > $lastUpdate)
还要记住这是一个通知。虽然我提倡干净的代码,但严格来说这不是一个错误。您可以让json_decode返回一个数组,将其设置为true作为第二个参数。我想知道为什么上面的方法不起作用。是的。但根据代码,它的格式不正确。因此,JSON或PHP代码需要更新。您可以通过代码所生成的数组上的JSON_编码的输出来判断。输入文件的源代码没有显示,但听起来不像是一个JSON数组,而是一行JSON对象。@jimp,这是一个很好的观点。我是从提供的东西开始工作的。OP应该用输入更新问题以确保。{“name”:“move”,“args”:[24300,50],“timestamp”:1352223678463}^上面是输入,也会更新问题。为什么会这样?您从未检查过失败:)您的错误(对象不能作为数组访问。)和PHP冲突,是哪一个?还有,哪一行是第23行?啊,那是我的错误。编辑以将访问反映为数组<代码>如果($decodedEvent->timestamp>$lastUpdate){