1

I have a JSON array like below. I want to print only the values of the name. But I am getting undefined index name and getting value of name.below is my json.

[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]

my code

foreach($doc_array as $data => $mydata)
    {
          foreach($mydata as $key=>$val)
          {
              echo $val['name'];
          }
    }

How to get the values of name from docProfile? Any help would be greatly appreciated

user3408779
  • 981
  • 2
  • 19
  • 43

4 Answers4

2

Inside your foreach you don't need to loop again since docProfile is an index of the json object array

Just simple access it

echo $mydata['docProfile']['name'].'<br>';

so your foreach would be like this

foreach($doc_array as $data => $mydata) {
    echo $mydata['docProfile']['name'].'<br>';
}

Demo

Beginner
  • 4,118
  • 3
  • 17
  • 26
1

Try to something Like this.

<?php
$string = '[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';

$arr = json_decode($string, true);
echo $arr[0]['docProfile']['name'];
?>
Pravin Vavadiya
  • 3,195
  • 1
  • 17
  • 34
0

This array just have one row but if your array have more row you can use it; you need to decode JSON at first.

$doc_array =json_decode($doc_array ,true);

foreach($doc_array as $key=> $val){
     $val['docProfile']['name']  
}
AAZ
  • 51
  • 7
0
<?php
    $json_str='[{"docId":{"id":"57dd70252a896558e573a0c8"},"docProfile":{"name":"gowtham","gender":null,"email":null,"mobile":"7406339908"},"docLocalInfo":{"username":"gowtham","otp":934343,"newPasswordToken":null,"tempMobile":"","adminVerfiy":null},"privateInfo":{"mciNumber":null,"aadharNumber":null,"panNumber":null},"tempHospitals":[],"bankInfo":null,"signupSteps":{"accountCreated":true,"otpValidated":true},"notification":null,"hospitals":[],"address":null}]';

    $json_arr = (array)json_decode($json_str,true);
    foreach($json_arr as $iarr => $ia)
    {
        foreach($ia["docProfile"] as $doc => $docDetails)
        {
            if($doc =="name")
            {
                echo $ia["docProfile"]["name"];
            }
        }
    }
?>

This code gives you the answer

Gunaseelan
  • 2,494
  • 5
  • 36
  • 43