2

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

4
  • What is happening? Are there any error messages? Commented Aug 23, 2011 at 8:48
  • var_dump($response) or print_r($response)? Commented Aug 23, 2011 at 8:49
  • i get this error: Invalid argument supplied for foreach() Commented Aug 23, 2011 at 8:52
  • How do I get the "data" value to use on foreach and parser all "apps" arrays ? Commented Aug 23, 2011 at 8:56

3 Answers 3

3

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,....}}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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
}

2 Comments

i get: Invalid argument supplied for foreach()
Here json_decode($data) return stdClass object that can't be use in foreach so it throws error. A good practice is to use is_array($data) before foreach. And for convert stdClass to array you can use json_decode($data, true).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.