The Sumo The Sumo - 1 year ago 73
PHP Question

How to return specific data from json_decode

I'm accessing data from an API using json_decode. The code I have returns the array of ALL the date (see below), but I want to return specific data such as 'name' or 'locale'.

$json_string = '';
$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata,true);
echo '<pre>';

This is what is returned (this is abbreviated to save space here):

array(1) {
array(2) {
string(79) ""
array(5) {
array(4) {
string(8) "06999618"
string(14) "United Kingdom"
string(14) "Duedil Limited"
string(51) ""

Answer Source

You could just use

$name = $obj['response']['data'][0]['name'];
$locale = $obj['response']['data'][0]['locale'];

if you have multiple return values, you could loop over them

foreach ($obj['response']['data'] as $item) {
    $name = $item['name'];
    $locale = $item['locale'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download