简化json_decode结果

时间:2013-09-24 08:11:28

标签: php json

这是一个简单的功能,通过cURL请求数据并获取JSON。我只是想在JSON中使用数据,但为什么它是很多stdclass对象。如何简化此代码?

<?php
function movieRequest()
{
    $url = "http://api.com/content/movies?format=json";
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $headers[] = "Content-type: application/json"; 
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

$data = movieRequest();
$data = (array) json_decode($data);
print_r(get_object_vars(get_object_vars($data['categories'])['Access-Channel'])['category']); //Need this data but it still has stdClass Object. 
?>

太多了'get_object_vars'。有没有更好的方法来获取数据?

1 个答案:

答案 0 :(得分:4)

您可以使用json_decode()的第二个参数,并将结果数组作为结果:

$data = movieRequest();
$data = json_decode($data, true );
print_r( $data['categories']['Access-Channel']['category'] ); 

来自文档:

  

<强> ASSOC

     

当为TRUE时,返回的对象将被转换为关联数组。