繁体   English   中英

在PHP中获取JSON对象,而不是数组

[英]Get JSON objects in PHP, not array

我用PHP编写了一个网站,该网站从Ive创建的另一个php-api获取JSONstring。 该字符串如下所示:

{
    "result": "true",
    "results": {
        "20": {
            "id": "20",
            "desc": "a b ct tr",
            "active": "1",
            "startdate": "2013-04-03",
            "starttimehour": "18",
            "starttimemin": "0",
            "enddate": "2013-04-03",
            "endtimehour": "22",
            "endtimemin": "0",
            "creator": "a"
        },
        "21": {
            "id": "21",
            "desc": "test",
            "active": "0",
            "startdate": "2013-04-04",
            "starttimehour": "18",
            "starttimemin": "0",
            "enddate": "2013-04-04",
            "endtimehour": "22",
            "endtimemin": "0",
            "creator": "a"
        }
    }
}

我已经找到了很多有关如何从JSONarray获取信息的答案,但是我这里没有使用数组。 所以问题是:如何获得标有20、21等的对象(这些数字是由服务器生成的,所以我不知道将返回哪些对象)。

还是应该重写我的api如何将JSON作为数组返回。 像这样:

{"result"="true", "results":[{...},{...},{...}]}
$json = json_decode($json_string, True);
foreach($json['results'] as $key => $value) {
    // access the number with $key and the associated object with $value
    echo 'Number: '.$key;
    echo 'Startdate: '.$value['startdate'];
}

我想你是通过POST获得json的,没有任何参数,例如

curl http://someapi.somedomain/someresource/ -X POST -d @data.json

所以基本上

$data = file_get_contents('php://input');
$object = json_decode($data);
print_r($object);

应该可以解决您的问题。 $ object将是您发布的json对象。

您确实以字符串形式获取JSON响应。 这就是JSON的工作方式。 要将数据“转换”为易于访问的格式和结构,可以使用一个名为json_decode()的PHP函数。

使用此功能时,您有两种选择-

  1. 将数据转换为数组。 json_decode($jsonString,true)
    如果使用此方法,则将像访问关联数组一样访问数据。 $jsonArray['results']['21']

  2. 将数据转换为对象。 json_decode($jsonString)
    使用这种方法,您将使用对象表示法遍历数据-
    $num = 21;
    $jsonObj->results->$num

首先,对字符串($ string)进行解码,然后可以遍历字符串并获取对象的所有属性。 请记住,使用-> prop而不是['prop']来访问属性。 这样,您不必以数组方式处理它。

$jsoned = json_decode($string);
    foreach($jsoned->results as $o) {
        foreach($o as $key => $value) {
            echo "The key is: ".$key." and the value is: ".$value."<br>";
        }
    }

工作示例将输出:

关键是:id和值是:20

关键是:desc,值是:ab ct tr

关键是:活动,值是:1

等等...

暂无
暂无

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

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