改进循环在 php 上抛出一个模式

improving loop throw a schema on php

这是有效的,但感觉确实如此 "dirty"

我有一个架构 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);
     }
}

这可能吗?我想让这段代码尽可能干净整洁

是的,您可以按照自己的方式进行。你只需要一些语法来清理。

在此示例中,$result 是一个关联数组,因此您可以像任何数组一样对其进行索引。

$result = json_decode($result, true);
foreach ($result as $mydata) {
    foreach ($mydata["bodySchema"]["properties"] as $propertyName => $schema){
          var_dump([$propertyName, $schema]);
    }
}

如果您更喜欢对象语法,请从 json_decode 中删除 true

$result = json_decode($result);
foreach ($result as $mydata) {
    foreach ($mydata->bodySchema->properties as $propertyName => $schema){
          var_dump([$propertyName, $schema]);
    }
}