Dr. Atul Tiwari
Dr. Atul Tiwari

Reputation: 1085

How to get String value from json_decode in php

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.

Upvotes: 1

Views: 12368

Answers (2)

Caal Saal VI
Caal Saal VI

Reputation: 302

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'];
?>

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74615

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;

Upvotes: 1

Related Questions