1

My json-data is as follows -

[{"name": "ram"}]

What I want is the value of name in a variable e.g., $fname. I have tried -

<?php
$jsondata = '[{"name": "ram"}]';
//$obj = json_decode($jsondata);
$obj = json_decode($jsondata,true);
print_r($obj); // This line outputs as :- Array ( [0] => Array ( [name] => ram ) ) 
//What I need is value of key
print_r($obj['name']);
foreach ($obj as $k=>$v){
echo $v;
}
?>

But I am unable to get desired output.

Dr. Atul Tiwari
  • 1,085
  • 5
  • 22
  • 46
  • `print_r($obj);` And you will see the structure of your decoded json string. (Wait a minute and you will have tones of vampires here) – Rizier123 Apr 04 '15 at 17:10
  • @Rizier123 it shows `Array ( [0] => Array ( [name] => ram ) ) ` using `print_r($obj)`, but I don't know how to use it, to get value of name – Dr. Atul Tiwari Apr 04 '15 at 17:12
  • 1
    [`RTM`](http://php.net/manual/en/language.types.array.php) – Rizier123 Apr 04 '15 at 17:13
  • 1
    @Rizier123, I just read the manual. I think in layman language, it can be said that - output of my decoded json is Array inside an array. thanks for the link – Dr. Atul Tiwari Apr 04 '15 at 17:44
  • ^ You got it! That's it! This is also why I let you look at the structure of the decoded json: `Array ( [0] => Array ( [name] => ram ) )` <-- See 2x array! So it's multidimensional. And the first dimension is `0` then `name` – Rizier123 Apr 04 '15 at 17:48

2 Answers2

1

Here how to get that value

<?php
$jsondata = '[{"name": "ram"}]';
$obj = json_decode($jsondata,true);
//In case have multiple array
foreach ($obj as $k){
echo $k['name'];
}
//else
$obj[0]['name'];

//if 
$jsondata = '{"name": "ram"}';
$obj = json_decode($jsondata,true);
//use 
echo $obj['name'];
?>
Caal Saal VI
  • 192
  • 2
  • 12
  • it works, but one question though, since my `json-data` contains only one `name`, wouldn't it be un-necessary to use `foreach`? if yes, then, what's the alternative for it? thanks. – Dr. Atul Tiwari Apr 04 '15 at 17:26
  • @Dr.AtulTiwari ^^ Look at the output again what your decoded json string prints! And read my manual link! (And that's why an answer should include an explanation) – Rizier123 Apr 04 '15 at 17:32
  • @Dr.AtulTiwari if $jsondata = '{"name": "ram"}'; you can use $obj['name'] or you can use $obj[0]['name'] for your current jsondata – Caal Saal VI Apr 04 '15 at 17:40
1

As your output indicates, your JSON string represents an array containing one object. As you know that you want a value contained within the first element, you can get it directly:

$jsondata = '[{"name": "ram"}]';
$obj = json_decode($jsondata, true);
$name = $obj[0]['name'];
echo $name;
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • thanks for the answer. But @Call Sall VI has pointed out the same in his comment and modified the answer too accordingly (can't select 2 best answers), though I can upvote it :) – Dr. Atul Tiwari Apr 04 '15 at 17:47