跟踪JSON数组的分层树

时间:2013-06-14 15:08:44

标签: php arrays json curl associative-array

我只是无法理解为什么我在foreach中获得'post'的未定义索引。这是我用来通过cURL对API进行身份验证的函数,获取JSON,缓存它并使用foreach推断出我需要的信息:

<?php
// JSON URL which should be requested
$json_url = 'https://api.del.icio.us/v1/posts/recent';

$username = 'USERNAME';  // authentication
$password = 'PASSWORD';  // authentication

// Initializing curl
$ch = curl_init( $json_url );

// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . ":" . $password   // authentication
);

// Setting curl options
curl_setopt_array( $ch, $options );



$cache_delicious = '/MY_DIR/'.sha1($json_url).'.json';

    if(file_exists($cache_delicious) && filemtime($cache_delicious) > time() - 1000){
        // if a cache file newer than 1000 seconds exist, use it
        $data_delicious = file_get_contents($cache_delicious);
    } else {

        $delicious_result = simplexml_load_string(curl_exec($ch));
        $data_delicious = json_encode($delicious_result);
        file_put_contents($cache_delicious, $data_delicious);
    }

    $obj = $data_delicious;

foreach (array_slice(json_decode($data_delicious, true), 0, 5) as $obj) {
    $delicious_title = str_replace('"', '\'', $obj['post']['@attributes']['description']);
    $delicious_url = htmlentities($obj['post']['@attributes']['href'], ENT_QUOTES, "UTF-8");
    $output = "<li><a rel=\"external nofollow\" title=\"$delicious_title\" href=\"$delicious_url\">$delicious_title</a></li>";
    echo $output;
}
?>

这是JSON(如果我做print_r($data_delicious);):

{
   "@attributes":{
      "tag":"",
      "user":"myusername"
   },
   "post":[
      {
         "@attributes":{
            "description":"MY FEED TITLE",
            "extended":"",
            "hash":"d00d03acd6e01e9c2e899184eab35273",
            "href":"http:\/\/myurl.com\/",
            "private":"no",
            "shared":"yes",
            "tag":"",
            "time":"2013-06-13T10:30:08Z"
         }
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

要将json_decode d个对象作为数组访问,您已将第二个参数设置为json_decode为true,否则它会创建对象而不是关联数组。

$data_delicious = json_encode($delicious_result, true);