PHP / JSON - 如何解析stdClass对象?

时间:2011-08-23 08:46:50

标签: php arrays json curl

我有一些JSON,我通过一些基本解析JSON并按如下方式对其进行解码的PHP运行它:

$request = array(
'object' => 'App',
'action' => 'getList',
'args' => array(
'sort' => 1,
'appsPerPage' => 15,
'page' => 1,
'deviceid' => 1));


$wrapper = array(
'request' => json_encode($request));

$wrapper = urlencode(json_encode($wrapper));

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://api.apptrackr.org/');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "request=$wrapper");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response);

结果:

    object(stdClass)#2 (3) { ["code"]=> int(200) ["data"]=> string(14100) "{"apps": {"id":303917165,"add_date":1314083737,"last_modification":1314083737,"name":"my Fish 3D Aquarium","seller":"

最后还有更少的“应用”...

现在,我试试这个:

    foreach ($response->apps as $app) {
    .......
    ......
    }

它不起作用......需要帮助。

感谢

3 个答案:

答案 0 :(得分:2)

看起来您的后端方法返回类似

的内容
{code:200, data: '{"apps":{"id":303917165, ....}"};

请注意,数据是 json_encoded string

解决此问题的简单方法是:

$response = json_decode($response);
$real_response = json_decode($response->data,true);
//$real_response is an array with 'apps' key containing your data

正确的方法是修复后端以仅返回数据,因此原始响应类似于

{"apps":{"id":303917165,....}}

答案 1 :(得分:0)

$response->apps不是数组。 $response->data是一个json格式的字符串。您可以使用json_decode将其转换为数组。

答案 2 :(得分:0)

IT看起来像你的对象: -

class Object {
    var code = 200;
    var data = "Big long JSON string here";
}

您应该执行类似

的操作
$data = json_decode($data);
foreach ($data->apps as $app)
{
    //do stuff here
}