3

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;
    }
}
lolbas
  • 794
  • 1
  • 9
  • 34

1 Answers1

1

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/>
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167