使用反射递归迭代结构并设置字段

2024年 2月 10日 20.7k 0

使用反射递归迭代结构并设置字段

php小编西瓜在本文中将介绍如何使用反射递归迭代结构并设置字段。反射是PHP中一种强大的特性,它允许我们在运行时获取并操作类、方法、属性等信息。递归迭代结构是一种常用的处理方式,它可以帮助我们遍历和操作复杂的数据结构。通过结合反射和递归迭代结构,我们可以轻松地获取并设置字段的值,从而实现更灵活、高效的编程。在接下来的内容中,我们将详细介绍这一过程,帮助读者更好地理解和应用这个技巧。

问题内容

我想构建使用反射设置结构体字段的程序。我让它适用于顶级字段,但我正在努力处理嵌套结构字段。如何迭代嵌套结构字段?

type Payload struct {
Type string `json:"type"`
SubItem *SubItem `json:"sub_item"`
}

type SubItem struct {
Foo string `json:"foo"`
}

func main() {
var payload Payload
setValue(&payload, "type", "test1")
setValue(&payload, "sub_item.foo", "test2")
}

func setValue(structPtr interface{}, key string, value string) {
structValue := reflect.Indirect(reflect.ValueOf(structPtr))
for i, subkey := range strings.Split(key, ".") {
isLast := i == len(strings.Split(key, "."))-1
var found bool
// this line is crashing with "reflect: call of reflect.Value.NumField on zero Value"
for i := 0; i 登录后复制

解决方法

使用此功能:

func setvalue(p interface{}, key string, value interface{}) {
v := reflect.valueof(p)

// loop through the names in key to find the target field.
for _, name := range strings.split(key, ".") {

// if the value is pointer, then
// - allocate value if ptr is nil.
// - indirect ptr
for v.kind() == reflect.ptr {
if v.isnil() {
v.set(reflect.new(v.type().elem()))
}
v = v.elem()
}

// we expect that the value is struct. find the
// named field.
v = findjsonfield(v, name)
if !v.isvalid() {
panic(fmt.sprintf("could not find field %s", key))
}
}

// set the field.
v.set(reflect.valueof(value))
}

登录后复制

函数 findjsonfield 通过字段的 json 标签查找结构体字段:

func findJSONField(v reflect.Value, name string) reflect.Value {
t := v.Type()
for i := 0; i 登录后复制

https://www.php.cn/link/e4848ea6b69df2c66c87e2877e74726b

以上就是使用反射递归迭代结构并设置字段的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论