motioz
motioz

Reputation: 662

PHP/JSON - how to parser that stdClass Object?

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,
'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

Upvotes: 2

Views: 4646

Answers (3)

Mez
Mez

Reputation: 24953

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
}

Upvotes: 0

J0HN
J0HN

Reputation: 26941

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,....}}

Upvotes: 3

xdazz
xdazz

Reputation: 160873

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

Upvotes: 0

Related Questions