如何使用PHP从JSON访问另一个对象内的类的成员 [英] How to access a member of a class which is inside another object from JSON using PHP

查看:120
本文介绍了如何使用PHP从JSON访问另一个对象内的类的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a JSON String like this

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

我想访问该功能中的状态码. 这就是我尝试过的:

I want to access the status code in the function. this is what i tried:

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

echo $responseObj->status->code;

现在这行不通了.有人可以指出我正确的方向.我认为

now this isnt working. Can someone point me in the right direction. I think that

$responseObj->status->code

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

is the wrong syntax to use. What is the right syntax. I am using PHP 5.1.6 , this doesnt have the inbuilt json_decode function. So I am using a third party Class to convert. I use the following third party class

  • @package Services_JSON
  • @author Michal Migurski
  • @author Matt Knapp
  • @author Brett Stimmerman
  • @copyright 2005 Michal Migurski
  • @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
  • @license http://www.opensource.org/licenses/bsd-license.php
  • @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198

推荐答案

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

You should give PHP's json_decode() a try:

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

对于PEARS的Services_JSON类(文档):

For PEARS's Services_JSON Class (Documentation):

// 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;

这篇关于如何使用PHP从JSON访问另一个对象内的类的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆