0

I am stuck with this Json data:

I have this info in a variable:

$mydata= '{"success":true,"data":[{"sku":203823,"issoldout":false,"isShowDiscount":false,"discount":0,"currencycode":"USD","currencysymbol":"US$","price":"10.20","listprice":"","adddate":"4/23/2013"}]}';

I have managed to tell if success is true or not by doing this:

$obj = JSON_decode($mydata, true);

if ($obj['success'] != 1) {
    print 'Does Not Exist<br />';
}
else{
    print $obj['success']."<br/>";
}

where echo $obj['success']; is equal to 1 if True and 0 if False.

What is getting me stuck is how to get at the keys in the "data":[] array.

I tried print $obj['data'][0]; and print $obj['data']['sku']; but both returned nothing.

Any ideas on how to get the info out would be welcomed.

3
  • 1
    Use single quotes around the mydata string. Commented May 14, 2013 at 2:12
  • Also missing semi colon on the end of your string. JSON_decode is actuall json_decode. Commented May 14, 2013 at 2:16
  • fixed. Just a copy-paste mistake. Commented May 14, 2013 at 2:27

3 Answers 3

5

$data is an array so:

echo $obj['data']; should print "Array"

echo $obj['data'][0]['sku']; should print "203823"

Sign up to request clarification or add additional context in comments.

Comments

1
 $mydata= "{"success":true,"data":[{...}]}"

$mydata['data'] contains an array of objects.

In json the {..} contents are for objects, and [..] are for arrays.

So you would go

foreach($obj['data'] as $items)
{
    echo $items['sku'];
}

I'm using foreach because there could be more than one object in your JSON result.

Comments

0

See my comments, this code runs successfully.

$mydata= '{"success":true,"data":[{"sku":203823,"issoldout":false,"isShowDiscount":false,"discount":0,"currencycode":"USD","currencysymbol":"US$","price":"10.20","listprice":"","adddate":"4/23/2013"}]}';

$obj = json_decode($mydata, TRUE);

if ($obj['success'] != 1) {
  print 'Does Not Exist<br />';
}
else{
  print $obj['success']."<br/>";
}

Comments

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.