douye4254 2016-05-13 04:06
浏览 22
已采纳

使用php获取json模式的所有元素

I really need help on this one.

I have the following Json Schema:

{
    "url": "http://www.google.com",
    "bodySchema": {
        "type": "object",
        "properties": {
            "SKU": {
                "sync": "True",
                "mapTo": "SKU",
                "type": "string"
            },
            "WareHouseId": {
                "sync": "False",
                "mapTo": "",
                "type": "integer"
            },
            "Stock": {
                "sync": "True",
                "mapTo": "Stock",
                "type": "integer"
            }
        },
        "required": {
            "0": "SKU",
            "1": "Stock"
        }
    }
}

I would like to retrieve all elements and check if they are required or not,

On the first part (Getting all elements)

What I'm doing is:

foreach ($this->methods as $data) {
    if(!empty($data['bodySchema']->properties)){
    }
}

But my problem is that I have no way to get the SKU, WarehouseID or Stock, because it's not a key nor anything of the kind.

For my second issue what I was thinking, was to put all required as string and do a loop through them, but if there is any alternative would be glad to know.

  • 写回答

1条回答 默认 最新

  • dpb35161 2016-05-13 04:14
    关注

    You can get the properties out with a simple loop:

    foreach ($data->bodySchema->properties as $key => $value) {
        // ..
    }
    

    If you want to add the required field to the results from above, you can do it like so:

    foreach ($data->bodySchema->required as $required) {
        $data->bodySchema->properties->$required->required = true;
    }
    

    Example with objects or with arrays.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 求解vmware的网络模式问题
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳
  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥30 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?