-3
<?php
$json = '{"data":"listCountry","country":[{"zip":11023,"code":"NY"}],"phone":"+1458589994","name":{"firstname":"John","lastname":"Cannor"},"status":"MEMBER"
}';
$a=json_decode($json);
print_r($a->{'country'}[0]->{'zip'}); //output "11023" Success
echo "<br />";
print_r($a->{'country'}[0]->{'code'}); //output "NY" Success
echo "<br />";
echo $a->phone;  //output "+1458589994" Success
echo "<br />";
echo $a->status;  //output "MEMBER" Success
//this my problem
echo "<br />";
print_r($a->{'name'}[0]->{'firstname'}); //output blank or error
echo "<br />";
print_r($a->{'name'}[0]->{'lastname'}); //output blank or error
?>

how do I retrieve the json string "name": {"firstname": "John", "lastname": "Cannor"} to php in my json ? i am put php code

print_r($a->{'name'}[0]->{'firstname'});

and

print_r($a->{'name'}[0]->{'lastname'}); 

is error or blank page

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Eyus Wap
  • 39
  • 3
  • 1
    You don't need the braces and quotes for the property names when they're single words. You really only need them when it's non-standard properties such as `this-property` or `this property` – aynber Apr 08 '20 at 16:41

3 Answers3

2
<?php
$json = '{"data":"listCountry","country":[{"zip":11023,"code":"NY"}],"phone":"+1458589994","name":{"firstname":"John","lastname":"Cannor"},"status":"MEMBER"
}';
$a=json_decode($json, true);
echo $a['name']['firstname'];

should work

smokernd
  • 31
  • 3
0

name is not a array.

try

print_r($a->{'name'}->{'lastname'})
JsMoreno
  • 93
  • 1
  • 6
  • Remember that print_r () function is only neccesary to print a array, For print strings you can use echo. – JsMoreno Apr 08 '20 at 16:50
0

Try this:

print_r($a->{'name'}->{'firstname'});

You can also simplify your code:

print_r($a->name->firstname);

$a->name is not an array in your JSON.

saulotoledo
  • 1,737
  • 3
  • 19
  • 36