The incoming interface{} will be converted to []map[string]interface{}.
Raw data type is []map[string]interface{} :
[
{
"ID": 1,
"Name": "Root",
"ParentID": 0,
"Path": "Root"
},
{
"ID": 2,
"Name": "Ball",
"ParentID": 1,
"Path": "Root/Ball"
},
{
"ID": 3,
"Name": "Foot",
"ParentID": 2,
"Depth": 2,
"Path": "Root/Ball/Foot"
}
]
Hope to get type for json:
[
{
"ID": 1,
"Name": "Root",
"ParentID": 0,
"Path": "Root",
"Child": {
"ID": 2,
"Name": "Ball",
"ParentID": 1,
"Path": "Root/Ball",
"Child": {
"ID": 3,
"Name": "Foot",
"ParentID": 2,
"Depth": 2,
"Path": "Root/Ball/Foot"
}
}
}
]
if methods of php:
$data = Raw data is array()...
$result = array();
$temp = array();
foreach($data as $item) {
if($item['ParentID'] == 0) {
$result[$item['ID']] = $item;
$temp[$item['ID']] =& $result[$item['ID']];
}else {
$temp[$item['ParentID']][$item['ID']] = $item;
$temp[$item['ID']] =& $temp[$item['ParentID']][$item['ID']];
}
}
return $result
golang is not run:
func tree(array interface{}) map[int]*[]map[string]interface{} {
results := make(map[int]*map[string]interface{})
temp := make(map[int]map[string]*map[string]interface{})
for _, item := range maps(array) {
id := int(item["ID"].(float64))
pid := int(item["ParentID"].(float64))
if pid == 0 {
results[id] = item
temp[id]["c"] = &results[id]
} else {
temp[pid]["c"] = item
temp[id] = &temp[pid]["c"]
}
}
return results
}
func maps(val interface{}) []map[string]interface{} {
if b, err := json.Marshal(val); err == nil {
var maps []map[string]interface{}
json.Unmarshal(b, &maps)
return maps
}
return nil
}
my english is not good. only be expressed by way of code and google translation. Hope to get everyone's help.