我如何访问从以下数组中的单个值在php


Tumblr API How do I access the individual values from the following array in php

我正在使用tumblr API和以下代码:

$var = xhttp::toQueryArray($response['body']);
print_r($var);

在屏幕上打印如下内容:

Array ( [{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lukebream","likes":0,"following":8,"default_post_format":"html","blogs":[{"name":"lukebream","url":"http:'/'/lukebream.tumblr.com'/","followers":5,"primary":true,"title":"Untitled","admin":true,"queue":0,"ask":false,"tweet":"N"}]}}}] => )

如何访问单个元素并将它们赋值给变量?

下面是我完成的内容:

$tumblr->set_token($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$data = array();
$data['post'] = array();        
$response = $tumblr->fetch('http://api.tumblr.com/v2/user/info', $data);    
if($response['successful']) {
    echo $response['json']['response']['url'];
} else {
    echo "api call failed. {$response[body]}<br><br>";
}

这是JSON,可以用json_decode()

解析

用法示例:

//I used file_get_contents() to keep things simple
$jsonData = file_get_contents("http://api.tumblr.com/v2/blog/lukebream.tumblr.com/info?api_key=<api_key_here>"); 

$jsonData包含:

{
    "meta":{
        "status":200,
        "msg":"OK"
        },
    "response":{
        "blog":{
            "title":"Untitled",
            "posts":61,
            "name":"lukebream",
            "url":"http:'/'/lukebream.tumblr.com'/",
            "updated":1321830278,
            "description":"",
            "ask":false,
            "likes":0
            }
        }
}

经过json_decode()后,我们得到一个PHP对象,所以:

$obj = json_decode($jsonData);

将返回:

stdClass Object
(
    [meta] => stdClass Object
        (
            [status] => 200
            [msg] => OK
        )
    [response] => stdClass Object
        (
            [blog] => stdClass Object
                (
                    [title] => Untitled
                    [posts] => 61
                    [name] => lukebream
                    [url] => http://lukebream.tumblr.com/
                    [updated] => 1321830278
                    [description] => 
                    [ask] => 
                    [likes] => 0
                )
        )
)

你也可以使用json_decode($str, TRUE):这将返回一个ARRAY而不是一个对象,更容易玩!