从JSON_DECODE获取某些信息

时间:2013-08-05 20:09:07

标签: php json

我试图尽可能地解释这个,请问我现在还不清楚。 我正在使用API​​获取有关传感器的大量信息。

这是类

中的方法
public function getSensors()
 {
     $params = array();
     return json_decode($this->consumer->sendRequest(constant('REQUEST_URI').'/sensors/list', $params, 'GET')->getBody());

在我的 index.php

$params = array('id'=> XXXXXX); 
$response = $consumer->sendRequest(constant('REQUEST_URI').'/sensor/info', $params,'GET');

echo json_decode($response->getBody());

这给了我一大堆这样的信息:

{"id":"xxxxx","client":"xxxx","name":"xxxxx","lastUpdated": xxxx}

我只想使用某些此信息。

这是getBody()方法 -

public function getBody() {
    if (self::METHOD_POST == $this->method && (!empty($this->postParams) || !empty($this->uploads))) {

        if (0 === strpos($this->headers['content-type'], 'application/x-www-form-urlencoded')) {

            $body = http_build_query($this->postParams, '', '&');

            if (!$this->getConfig('use_brackets')) {

                $body = preg_replace('/%5B\d+%5D=/', '=', $body);

            }

            // support RFC 3986 by not encoding '~' symbol (request #15368)

            return str_replace('%7E', '~', $body);



        } elseif (0 === strpos($this->headers['content-type'], 'multipart/form-data')) {

            require_once 'HTTP/Request2/MultipartBody.php';

            return new HTTP_Request2_MultipartBody(

                $this->postParams, $this->uploads, $this->getConfig('use_brackets')

            );

        }

    }

    return $this->body;

}

1 个答案:

答案 0 :(得分:0)

如果您使用的是API,则无法控制您获得的信息,除非API定义了这样做的方法。如果您正在阅读传感器,那么这不太可能是一种选择。

然而,你可以忽略你不需要的东西。

例如:

$myArray = json_decode('{"id":"xxxxx","client":"xxxx","name":"xxxxx","lastUpdated": xxxx}');
$mySubset = array($myArray['id'], $myArray['lastUpdated']);

我只是用json_decode来说明这一点。从您的注释看起来getBody()返回一个数组,但您报告的错误消息指向一个对象。

对于数组,您可以使用

$myResp = $response->getBody();
$myId = $myResp['id'];

对于对象,您可以使用

$myResp = $response->getBody();
$myId = $myResp->id;

道歉,如果我没有达到这个标准 - 我在这里开了一点盲目!

相关问题