gpt4 book ai didi

php - 从 json 对象创建 php 类树

转载 作者:行者123 更新时间:2023-12-02 21:23:49 24 4
gpt4 key购买 nike

编辑

好吧,看来我真的不擅长描述我的问题。我发现this generator在网上,我正在寻找的是完全相同的东西,但对于 php 代码。有什么想法吗?


原始问题

我愿意从 json 表示(API 映射到对象)构建许多 php 类,为此我想转换它:

{
"success": true,
"domains": [
{
"id": "13",
"manual": "0",
"name": "silo3.mobi",
"lastname": "Doe",
"firstname": "John",
"cid": "1",
"period": "1",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "namesilo",
"next_due": "2012-12-12",
"expires": "2012-12-12",
"status": "Active",
"type": "Register",
"date_created": "2011-12-12",
"autorenew": "1",
"reglock": "1",
"idprotection": "1"
},
{
"id": "11",
"manual": "0",
"name": "netearthorg.org",
"lastname": "Doe",
"firstname": "John",
"cid": "1",
"period": "1",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "NetEarthOne",
"next_due": "2012-11-22",
"expires": "2012-11-22",
"status": "Active",
"type": "Register",
"date_created": "2011-11-22",
"autorenew": "1",
"reglock": "1",
"idprotection": "0"
},
{
"id": "10",
"manual": "0",
"name": "hbappreseller.co.uk",
"lastname": "Blue",
"firstname": "Mike",
"cid": "6",
"period": "2",
"recurring_amount": "9.95",
"currency_id": "0",
"module": "NetEarthOne",
"next_due": "2012-11-22",
"expires": "0000-00-00",
"status": "Pending",
"type": "Register",
"date_created": "0000-00-00",
"autorenew": "1",
"reglock": "0",
"idprotection": "0"
}
],
"call": "getDomains",
"server_time": 1323793581
}

具有 bool:success 属性的对象、“域”对象数组等。

这并不难做到,我可以自己开发,但我想知道是否有一些 php 库可以处理这个问题,还没有找到

编辑

好吧,我还没有很好地解释自己,我想,我想做的是构建一个 php 类文件,并依赖于其他类等等,这样我就可以匹配 json 结构。

例如,给定的 json 应生成以下内容:

class Domain {
protected $id;
protected $manual;
protected $name;
protected $lastname;
protected $firstname;
protected $cid;
protected $period;
protected $recurring_amount;
// and so on
}

目的是为具有复杂对象的 WSDL 提供服务,并避免在对原始 API 进行任何修改时使 wsdl 签名演变(自定义类不会动态更改,仅在需要时更改,因此 WSDL 将保持不变)

API 生成数百个 json 对象,其中一些共享属性,因此这样做的目的是有一个全局方法来处理所有 json 字符串并构建或获取构建的对象,例如两个 json 可以具有“域”属性,所以第一次我想生成一个名为 Domain 的类(如果 property=array 然后创建属性名称为 -S 的文件并填充属性,然后保存到文件以供进一步使用)

最佳答案

假设您的 JSON 对象存储在 $json 中,那么您可以像这样动态创建一个类 -

$data = json_decode($json, true);

$class = new Domain();
foreach ($data AS $key => $value) $class->{$key} = $value;

如果您想要一种更通用的方法,假设您想动态更改类名称 -

$data = json_decode($json, true);

$className = "Domain"; // Or assign it to something else like pick from DB, from JSON from anywhere.
$class = new {$className}();
foreach ($data AS $key => $value) $class->{$key} = $value;

关于php - 从 json 对象创建 php 类树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25991993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com