Go語言轉化php數(shù)組的示例代碼
更新時間:2023年11月01日 10:52:19 作者:lxw1844912514
這篇文章主要為大家詳細介紹了Go語言如何實現(xiàn)轉化php數(shù)組的相關知識,文中的示例代碼講解詳細,對我們深入學習GO語言有一定的幫助,需要的可以參考下
php程序
$str = <<<EOF {"操作源":"任意","數(shù)據(jù)庫":"任意","語句類型":"CREATE DATABASE;DROP DATABASE;ALTER DATABASE","影響行數(shù)":"不涉及","告警閾值":"執(zhí)行1次"} EOF; $data = [ 'title' => '標題', 'list' => $str ]; $const = ['operate_account' => '操作源', 'db_name' => '數(shù)據(jù)庫', 'sql_type' => '語句類型', 'rows' => '影響行數(shù)', 'alarm_line' => '告警閾值']; $data['list'] = json_decode($data['list'], 320); $newArr2['title']=$data['title']; foreach ($data['list'] as $key => $v) { $newArr2['content'][array_search($key,$const)]= $v; } dd($data); dd($newArr2); function dd($param) { echo "<pre>"; print_r($param); echo "<pre>"; }
轉化go語言
package main import ( "encoding/json" "github.com/gin-gonic/gin" ) type Data struct { Title string `json:"title"` Content map[string]string `json:"content"` } func main() { r := gin.Default() // 多行JSON字符串 jsonStr := `{ "操作源": "任意", "數(shù)據(jù)庫": "任意", "語句類型": "CREATE DATABASE;DROP DATABASE;ALTER DATABASE", "影響行數(shù)": "不涉及", "告警閾值": "執(zhí)行1次" }` // 轉化為Go結構體 var data map[string]interface{} if err := json.Unmarshal([]byte(jsonStr), &data); err != nil { panic("無法解析JSON數(shù)據(jù)") } // 定義常量映射 constMap := map[string]string{ "操作源": "operate_account", "數(shù)據(jù)庫": "db_name", "語句類型": "sql_type", "影響行數(shù)": "rows", "告警閾值": "alarm_line", } // 創(chuàng)建新的數(shù)據(jù)結構 var newArr2 Data newArr2.Title = "標題" // 創(chuàng)建內(nèi)容的映射 newArr2.Content = make(map[string]string) // 遍歷data中的數(shù)據(jù) for key, value := range data { // 查找映射關系 mappedKey, exists := constMap[key] //fmt.Println(key, value, exists, constMap["數(shù)據(jù)庫"], mappedKey) //os.Exit(2232) if exists { newArr2.Content[mappedKey] = value.(string) } } r.GET("/data", func(c *gin.Context) { c.JSON(200, newArr2) }) r.Run(":8081") }
轉化結果:
到此這篇關于Go語言轉化php數(shù)組的示例代碼的文章就介紹到這了,更多相關go轉化php數(shù)組內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!