繁体   English   中英

如何使用PHP从JSON访问另一个对象内的类的成员

[英]How to access a member of a class which is inside another object from JSON using PHP

我有一个像这样的JSON字符串

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

我想访问函数中的状态码。 这是我尝试的:

$responseObj=jsonService->decode($test);//this converts the string into an Object

echo $responseObj->status->code;

现在这是行不通的。 有人可以指出我正确的方向。 我觉得

$responseObj->status->code

是使用错误的语法。 什么是正确的语法。 我正在使用PHP 5.1.6,它没有内置的json_decode函数。 所以我正在使用第三方类进行转换。 我使用以下第三方课程

您可以使用json_decode()完成此任务。 另外,您的输入字符串应带有引号:

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

$responseObj = json_decode($test);

echo $responseObj->status->code;

不知道您在做什么jsonService,但这对我有用:

$json = '{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';

$result = json_decode($json);

echo $result->status->code;

您应该尝试使用PHP的json_decode():

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';
$responseObj = json_decode($test);
echo $responseObj->status->code;

对于PEARS的Services_JSON类( 文档 ):

// create a new instance of Services_JSON
$jsonService = new Services_JSON();

$test='{"var1":null,"var3":null,"status":{"code":150,"message":"blah blah"}}';
$jsonService->decode($test);
echo $responseObj->status->code;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM