这很有效,但感觉真的很“脏”
我有一个架构json,如:
[
{
"url": "http://www.google.com/api/updateVariable",
"verb": "POST",
"bodySchema": {
"type": "object",
"properties": {
"StoreId": {
"sync": "True",
"type": "integer"
},
"SKU": {
"sync": "True",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"type": "integer"
},
"Stock": {
"sync": "True",
"type": "integer"
}
},
"required": [
"StoreId",
"SKU",
"Stock"
]
}
},
{
"url": "http://www.google.com/api/insertVariable",
"verb": "POST",
"bodySchema": {
"type": "object",
"properties": {
"StoreId": {
"sync": "True",
"type": "integer"
},
"SKU": {
"sync": "True",
"type": "string"
},
"WareHouseId": {
"sync": "False",
"type": "integer"
},
"Description": {
"sync": "True",
"type": "integer"
}
},
"required": [
"StoreId",
"SKU",
"Description"
]
}
}
]
我想循环抛出所有属性(再次,这是有效的)
$result=json_decode($result, true);
while($item = array_shift($result)){
foreach ($item as $key => $value){
if($key=="bodySchema"){
foreach ($value as $key2 => $value3){
if($key2==properties)
var_dump($value3);
}
}
}
}
我想拥有的是:
$result=json_decode($result, true);
foreach($result as $mydata){
foreach($mydata->bodySchema->properties as $values){
var_dump($values->value);
}
}
这可能吗?我想保持这段代码尽可能干净整洁
答案 0 :(得分:1)
是的,你可以按照你想要的方式去做。你只需要一些语法来清理。
在此示例中,$result
是一个关联数组,因此您可以像任何数组一样索引它。
$result = json_decode($result, true);
foreach ($result as $mydata) {
foreach ($mydata["bodySchema"]["properties"] as $propertyName => $schema){
var_dump([$propertyName, $schema]);
}
}
如果您更喜欢对象语法,请从true
。
json_decode
$result = json_decode($result);
foreach ($result as $mydata) {
foreach ($mydata->bodySchema->properties as $propertyName => $schema){
var_dump([$propertyName, $schema]);
}
}