0

I have problem with accessing an object (stdClass) after json_decode.

I don't know why there is problem with - as part of th key. Here is my code:

$a = array('body'=>array('short-description'=>'its short description','detailed-description'=>'its detail descriptionb'),'title'=>'its a title');
$b = json_encode($a);
$c = json_decode($b);
var_dump($c->body->short-description);

The problem is I can't get the value of short-description because the key have -.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
sudeep777
  • 69
  • 2
  • 8

3 Answers3

2

Try like this

var_dump($c->body->{"short-description"});

You need to enclose it in braces.

chandresh_cool
  • 11,753
  • 3
  • 30
  • 45
1

Try;

$c = json_decode($b, true);

echo $c['body']['short']['short-description'];

The True Boolean converts it to a multi-dimensional array, and allows you to access the json that way.

Dom
  • 7,135
  • 1
  • 11
  • 13
0

Just wrap in brackets, such as:

var_dump($c->body->{'short-description'});
Malcolm Diggs
  • 455
  • 2
  • 7