### **JSON转数组**
```
// PHP
$json = '{"id":1,"title":"test","banner_list":[{"screen":"phone","image_list":["1.jpg","2.jpg"]},{"screen":"pad","image_list":["3.jpg","4.jpg"]}]}';
$array = json_decode($json, true);
// Go
package main
import (
"encoding/json"
"fmt"
)
type bannerList struct {
Screen string `json:"screen"`
BannerList []string `json:"banner_list"`
}
type banner struct {
ID int64 `json:"id"`
Title string `json:"title"`
BannerList []bannerList `json:"banner_list"`
}
func main() {
a := `{"id":1,"title":"test","banner_list":[{"screen":"phone","image_list":["1.jpg","2.jpg"]},{"screen":"pad","image_list":["3.jpg","4.jpg"]}]}`
var b banner
json.Unmarshal([]byte(a), &b)
fmt.Println(b.ID, b.Title)
}
```
*****
### **数组转JSON**
```
// PHP
$json = json_encode($array);
// Go
c, _ := json.Marshal(b)
```
*****
### **数组转字符串**
```
// PHP
$array = [1,2,3];
$str = implode(',', $array);
// Go
arr := []string{"1", "2", "3"}
str := strings.Join(arr, ",")
```
*****
### **字符串转数组**
```
// PHP
$str = '1,2,3';
$array = explode(',', $str);
// Go
str := "1,2,3"
list := strings.Split(str, ",")
```
*****
### **是否存在数组中**
```
// PHP
$str = "1";
$arr = ["1", "2", "3"];
if (in_array($str, $arr)) {
exit('true');
}
exit('false');
// Go
// 数据类型需要一致
func InArray(val interface{}, array interface{}) bool {
switch reflect.TypeOf(array).Kind() {
case reflect.Slice:
s := reflect.ValueOf(array)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
return true
}
}
}
return false
}
func main() {
str := "1"
arr := []string{"1", "2", "3"}
if InArray(str, arr) {
fmt.Println("true")
} else {
fmt.Println("false")
}
}
```