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.

5
  • 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) Commented Apr 4, 2015 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 Commented Apr 4, 2015 at 17:12
  • 1
    RTM Commented Apr 4, 2015 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 Commented Apr 4, 2015 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 Commented Apr 4, 2015 at 17:48

2 Answers 2

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'];
?>
Sign up to request clarification or add additional context in comments.

3 Comments

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.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)
@Dr.AtulTiwari if $jsondata = '{"name": "ram"}'; you can use $obj['name'] or you can use $obj[0]['name'] for your current jsondata
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;

1 Comment

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 :)

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.