$arr = [
[
"a" => 1,
"b" => 2,
],
[
"c" => 1,
"d" => 2,
],
[
"e" => 1,
"f" => 2,
],
];
这个 $arr 就是一个数组,它是由几个数组对象组成,PHP 数组可以这样非常灵活随意的赋值,数字,字符串,类等等,什么类型的结构都可以直接这样表示。
package main
import (
"encoding/json"
"fmt"
)
func main() {
npc1 := make(map[string]string)
npc1["id"] = "2212"
npc1["type"] = "23"
npc1["effect"] = "23"
npc1["localX"] = "44"
npc1["localY"] = "55"
npc1["pathId"] = "23"
npc1["shape"] = "0.8"
npc2 := make(map[string]string)
npc2["id"] = "2212"
npc2["type"] = "23"
npc2["effect"] = "23"
npc2["localX"] = "44"
npc2["localY"] = "55"
npc2["pathId"] = "23"
npc2["shape"] = "0.8"
var npcList = make([]interface{}, 0)
npcList = append(npcList, npc1, npc2)
out, _ := json.Marshal(npcList)
fmt.Print(string(out))
/**
[{"effect":"23","id":"2212","localX":"44","localY":"55","pathId":"23","shape":"0.8","type":"23"},{"effect":"23","id":"2212","localX":"44","localY":"55","pathId
":"23","shape":"0.8","type":"23"}]
**/
}在 Golang 中,这里面的数组相当于 map,那么如何表示这样的结构呢?
看以下示例,有两个 map 类型数据,分别是 npc1 和 npc2,通过初始化一个切片保存 interface 类型数据,将 map 类型数据追究到切片,然后通过 json 序列化后得到的结果看,符合上面 PHP 例子的数据格式。代码如下:
这篇博客介绍了如何在Golang中使用切片和接口来实现类似PHP数组的灵活性。示例展示了如何将多个map转换为interface{}类型的切片,并通过json.Marshal进行序列化,以达到存储不同结构数据的目的。
1407

被折叠的 条评论
为什么被折叠?



