让我们考虑这个解决方案:
arrDetails := map[int]map[string]string{}
index := 0
for _, orderdetails := range ordersfromdb {
arrDetails[index] = map[string]string{} // you have to initialize map
arrDetails[index]["OrderNumber"] = "001"
arrDetails[index]["customernum"] = "cust_001"
arrDetails[index]["orderstatus"] = "open"
arrDetails[index]["orderprice"] = "200"
index++
}
要将结果转换为 json(正如我看到你在对@liao yu 的回答的评论中提出的问题),我们应该学习更多关于标签的知识:
import (
"encoding/json"
"fmt"
)
type OrderDetails struct {
Number string `json:"number"`
Customer string `json:"customer"`
Status string `json:"status"`
Price string `json:"price"`
}
func main() {
ordersfromdb := []int{1, 2, 3}
var arrDetails []OrderDetails
for _, v := range ordersfromdb {
arrDetails = append(arrDetails, OrderDetails{
Number: fmt.Sprintf("order_number_%v", v),
Customer: fmt.Sprintf("customer_%v", v),
Status: fmt.Sprintf("order_status_%v", v),
Price: fmt.Sprintf("$%v", v),
})
}
data, err := json.Marshal(arrDetails)
if err != nil {
panic(err)
}
fmt.Println(string(data))
}