【发布时间】:2017-04-06 21:04:14
【问题描述】:
传入的接口{}将被转换为[]map[string]interface{}。
原始数据类型为 []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"
}
]
希望得到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 的 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 没有运行:
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
}
我的英语不好。 只能通过代码和谷歌翻译的方式表达。 希望能得到大家的帮助。
【问题讨论】:
-
请付出一些努力。我们不是来为您编码的。您必须编写代码,我们会帮助您解决途中遇到的任何问题。
-
@nemo 对不起,我的错。
-
你为什么在 PHP 中使用
= &? -
@md2perpe 这不是递归,通过指针进行数据处理。
-
PHP 没有指针。 PHP 有参考。 PHP 还具有“写入时复制”,这意味着如果您执行
$x = $y,则$y不会被克隆,而只会被引用,直到将某些内容写入$y(例如$y['name'] = "Charlie")。