André Luiz André Luiz - 4 months ago 12
JSON Question

PhP - how to get the name of these objects

I'm new to PhP and I'm having trouble to figure out how to achieve one simple thing. I'm making a method which will return an array with key and value matching a json schema to a json data. By the way is there something that does it already?

Back to my question: I have this schema:

$demoSchema = '
{
"type":"object",
"properties":{
"firstName":{"title":"First name", "type":"string", "pattern":"^[a-z]+$"},
"lastName":{"title":"Last name", "type":"string","pattern":"^[a-z]+$"},
"age":{"title":"Age", "description":"Age in years","type":"integer","minimum":1},
"country":{"title":"Country", "type":"string", "enum":["Canada","US"]},
"address":{"title":"Address", "type":"string"},
"postalCode":{"title":"Postal Code", "type":"string"},
"city":{"title":"City", "type":"string"},
"province_ca":{"title":"Province", "type":"string", "enum":["Ontario","Quebec"]},
"province_us":{"title":"State", "type":"string"}
},
"required":["firstName","lastName","country"]
}
';


Here is how I transform it in a array:

$obj_schema = (array)json_decode($demoSchema);


My problem by now is that I can't get the name of the objects within the properties objects:
firstName
,
lastName
, etc..

How can I get them? When I do this loop I can get the properties inside the object, which I need as well:

foreach ($obj_schema["properties"] as $item){
echo($item->title);
}


But I can't get the
firstName
,
lastName
, etc.. strings. How can I do that?

Answer
foreach ($obj_schema["properties"]  as $property => $item){
    echo($item->title);
    echo 'Property Name:'. $property;
}
Comments