tora0515
tora0515

Reputation: 2547

PHP Decoding Array Within Json Object

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.

Upvotes: 0

Views: 2649

Answers (3)

Reactgular
Reactgular

Reputation: 54741

 $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.

Upvotes: 1

shapeshifter
shapeshifter

Reputation: 2967

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/>";
}

Upvotes: 0

Cfreak
Cfreak

Reputation: 19309

$data is an array so:

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

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

Upvotes: 5

Related Questions