Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving keys and values from json

Tags:

json

php

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;
    }
}
like image 486
N B Sri Harsha Avatar asked Feb 23 '26 08:02

N B Sri Harsha


1 Answers

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/>
like image 64
Jeff Puckett Avatar answered Feb 26 '26 16:02

Jeff Puckett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!