我是PHP的新手,我很难弄清楚如何实现一个简单的事情。我正在创建一个方法,该方法将返回一个数组,其中键和值匹配JSON模式到JSON数据。顺便说一下,有什么东西可以做到吗?
回到我的问题:我有这个架构:
$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"]
}
';
以下是我在数组中对其进行转换的方法:
$obj_schema = (array)json_decode($demoSchema);
我现在的问题是我无法在属性对象中获取对象的名称:firstName
,lastName
等。
我怎样才能得到它们?当我执行此循环时,我可以获取对象内部的属性,我也需要:
foreach ($obj_schema["properties"] as $item){
echo($item->title);
}
但我无法获得firstName
,lastName
等字符串。我怎么能这样做?
答案 0 :(得分:2)
foreach ($obj_schema["properties"] as $property => $item){
echo($item->title);
echo 'Property Name:'. $property;
}
答案 1 :(得分:1)
这样做(首先将孔数据转换为数组):
$obj_schema = json_decode($demoSchema,true);#<--NoteA
foreach ($obj_schema["properties"] as $property => $item){
echo($property." ".$item['title']);
}
NoteA:true
将给定数据的孔转换为数组
答案 2 :(得分:0)
您不需要转换为数组,因为通过json_decode($demoSchema)
您将获得stdClass对象。所以你只能做:
$obj_schema = json_decode($demoSchema);
然后获取名字:
echo $obj_schema->properties->firstName->title;
或者你可以用foreach获得所有这些:
foreach ($obj_schema->properties as $item){
echo $item->title;
}