我有一个动态的多维数组,我需要从循环中动态填充。我该如何定义数组并填充数据。
这是我正在尝试的代码
var arrDetails[][]string
var index int = 0
for _, orderdetails := range ordersfromdb {
arrDetails[index]["OrderNumber"] = "001"
arrDetails[index]["customernum"] = "cust_001"
arrDetails[index]["orderstatus"] = "open"
arrDetails[index]["orderprice"] = "200"
index++
}
我面临的错误:
non-integer slice index "OrderNumber"
non-integer slice index "customernum"
non-integer slice index "orderstatus"
non-integer slice index "orderprice"
我已经在php中完成了同样的工作,并且效果完美:
for ($i=0;$i<5:$i++)
{
$arr_orderdetails[$i]["OrderNumber"] = "001";
$arr_orderdetails[$i]["customernum"] = "cust_001";
$arr_orderdetails[$i]["orderstatus"] = "open";
$arr_orderdetails[$i]["orderprice"] = "200";
}
我是golang的新手,无法找到哪里出了问题,非常感谢您的帮助。
谢谢:)
答案 0 :(得分:2)
让我们考虑以下解决方案:
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的答案的评论中提出疑问),我们应该了解有关tags的更多信息:
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))
}
答案 1 :(得分:0)
正如您在此处将arrDetails
变量定义为[][]string
的多维切片一样,这意味着您无法将string
分配到其keys
中,而可以将字符串分配为值。
您可以像下面提到的那样编写代码。
package main
import (
"fmt"
)
func main() {
var arrDetails [][]string
var s []string
var index int
for i:=0; i<5;i++ {
s = []string{"001", "cust_001", "open", "200"}
arrDetails = append(arrDetails, s)
index++
}
fmt.Printf("Hello, playground %+v", arrDetails )
}
或者,如果您想要keys
和value
配对,则必须将map
用作:
var arrDetails map[string]string
答案 2 :(得分:0)
根据评论中的volker建议,我将如下填充多维数组
arrDetails[index][0] = "001"
arrDetails[index][1] = "cust_001"
arrDetails[index][2] = "open"
arrDetails[index][3] = "200"
答案 3 :(得分:0)
您可以尝试以下操作:
import "fmt"
func main() {
var arrDetails []map[string]string
var index int = 0
//for _, orderdetails := range ordersfromdb {
for i:=0; i<5;i++ {
detail := make(map[string]string)
detail["OrderNumber"] = "001"
detail["customernum"] = "cust_001"
detail["orderstatus"] = "open"
detail["orderprice"] = "200"
arrDetails = append(arrDetails, detail)
index++
}
fmt.Printf("Hello, playground %+v", arrDetails )
}