开发者

PHP/JSON - how to parser that stdClass Object?

开发者 https://www.devze.com 2023-03-29 20:20 出处:网络
I have some JSON, and I\'ve run it through some PHP that basically parses the JSON and decodes it as follows:

I have some JSON, and I've run it through some PHP that basically parses the JSON and decodes it as follows:

$request = array(
'object' => 'App',
'action' => 'getList',
'args' => array(
'sort' => 1,
'appsPerPage' => 15,
'page' => 1,
开发者_JS百科'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);

result:

    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":"

and more few "apps" at the end ...

now, i try this:

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

it's not working...need help.

thanks


Looks like your backend method return something like

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

Note that data is json_encoded string.

The simple way to workaround this is:

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

The right way is to fix backend to return just data, so the raw response is something like

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


$response->apps is not an array. $response->data is a json format string. You can use json_decode to turn it to an array.


IT looks like your object is something like:-

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

You should do something like

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

精彩评论

暂无评论...
验证码 换一张
取 消