從結果集中取出某一列的值組裝成新的陣列

PHP_LHF發表於2022-02-09

從結果集中取出某一列的值組裝成新的陣列

package main

import (
    "fmt"
)

func main() {

    data := []map[string]string{
        {"name":"z","age":"18","sex":"nan"},
        {"name":"l","age":"19","sex":"nv"},
        {"name":"x","age":"20","sex":"nan"},
        {"name":"g","age":"18","sex":"nv"},
    }
    fieldname := "age"
    fmt.Println(sliceColumn(data,fieldname))
    // 輸出結果:[18 19 20 18]
}

func sliceColumn(data []map[string]string,fieldname string) (result []string) {
    for _,v := range data{
        result = append(result,v[fieldname])
    }
    return result
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章