擅长:python、mysql、java
<p>我可以用下面的方法来做</p>
<pre><code>data[]
data.append([-1, 0 ,"name1", 0])
data.append([0,1, "name2", 1])
data.append([1, 2, "name3", 1])
data.append([2 ,3, "name4", 2])
data.append([2 ,4, "name5" ,2])
data.append([1 ,5, "name6", 2])
data.append([5, 6, "name7", 3])
data.append([5, 7, "name8",1])
data.append([5, 7, "name9",2])
def listToDict(input):
root = {}
lookup = {}
for parent_id, id, name, attr in input:
if parent_id == -1:
root['name'] = name;
lookup[id] = root
else:
node = {'name': name}
lookup[parent_id].setdefault('children', []).append(node)
lookup[id] = node
return root
result = listToDict(data)
print result
print json.dumps(result)
</code></pre>
<p>在我的例子中,我的数据是来自一个数据库的结果集,所以我必须按如下方式循环遍历它</p>
<pre><code> for v in result:
values = [v[2], v[3], v[4], v[5]]
pc.append(values)
</code></pre>