我需要从由 php 代码生成的序列化字符串中获取值
所以我使用一个名为:php_serialize
的包来反序列化字符串,然后得到一个 interface{}
类型的结果。
但我不知道如何在结果中获取值。
这是代码:
package main
import (
"github.com/yvasiyarov/php_session_decoder/php_serialize"
"fmt"
)
func main() {
// this string is generated from php code
str := `a:3:{s:4:"name";s:3:"tom";s:3:"age";s:2:"23";s:7:"friends";a:2:{i:0;a:1:{s:4:"name";s:5:"jerry";}i:1;a:1:{s:4:"name";s:4:"jack";}}}`
decoder := php_serialize.NewUnSerializer(str)
if result, err := decoder.Decode(); err != nil {
panic(err)
} else {
fmt.Println(result)
}
}
打印结果为:
map[name:tom age:23 friends:map[0:map[name:jerry] 1:map[name:jack]]]
这个结果是一个php_serialize.PhpValue
类型,也就是interface{}
类型
下一步是如何获取结果中的值?
比如获取age
字段和值
最佳答案
你必须断言 result
到 map[string]interface
:
mResult := result.(map[string]interface{})
fmt.Println(mResult["name"])
再一次为friends
断言:
mFriends := mResult["friends"].(map[int]map[string]interface{})
然后使用它:mFriends[0]["name"]
关于php - 如何从golang中的接口(interface)获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45705930/