N B Sri Harsha N B Sri Harsha - 6 months ago 8
JSON Question

Retrieving keys and values from json

I have this JSON string:

$json= '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}'


I want to retrieve all the values and keys from the json, output should look like:

id: 123
name: john smith
gender: MALE
phone:
number: +919999999999
numberType: MOBILE


I have tried this code but it fails to get the phone output:

$jsond = json_decode($json);
foreach($jsond->data as $row)
{
foreach($row as $key => $val)
{
echo $key . ': ' . $val;
}
}

Answer

This is exactly what array_walk_recursive is for:

<?php

$json = '{"data":[{"id":"123","name":"john smith","gender":"MALE","phone":[{"number":"+919999999999","numberType":"MOBILE"}]}]}';

$jsond = json_decode($json,true);

function test_print($val, $key)
{
    echo "$key : $val<br/>\n";
}

array_walk_recursive($jsond, 'test_print');

Resulting in this output:

id : 123<br/>
name : john smith<br/>
gender : MALE<br/>
number : +919999999999<br/>
numberType : MOBILE<br/>