沧海一幻觉
$arr = array( array('id'=>100, 'parentid'=>0, 'name'=>'a'), array('id'=>101, 'parentid'=>100, 'name'=>'a'), array('id'=>102, 'parentid'=>101, 'name'=>'a'), array('id'=>103, 'parentid'=>101, 'name'=>'a'),);$new = array();foreach ($arr as $a){ $new[$a['parentid']][] = $a;}$tree = createTree($new, array($arr[0]));print_r($tree);function createTree(&$list, $parent){ $tree = array(); foreach ($parent as $k=>$l){ if(isset($list[$l['id']])){ $l['data'] = createTree($list, $list[$l['id']]); } $tree[] = $l; } return $tree;}
有只小跳蛙
这是 C++ 代码示例,这不是一个完美的代码。您需要修改它以供您使用#if 0folder_id folder_name parent_id 1 parentFolder1 <NULL> 2 parentFolder2 <NULL> 3 subFolder1 1 4 subFolder2 1 5 subFolder3 3 6 subFolder4 2 7 subFolder5 5#endif#include<stdio.h>#include<iostream>#include<vector>#include<tuple>#include <bits/stdc++.h>#include<boost/property_tree/ptree.hpp>#include <boost/property_tree/json_parser.hpp>std::vector<std::tuple <int, std::string, int>> list;namespace pt = boost::property_tree;pt::ptree rootNode;int main () { list.push_back(std::make_tuple(1, "parentFolder1", 0)); list.push_back(std::make_tuple(2, "parentFolder2", 0)); list.push_back(std::make_tuple(3, "subFolder1", 1)); list.push_back(std::make_tuple(4, "subFolder2", 1)); list.push_back(std::make_tuple(5, "subFolder3", 3)); list.push_back(std::make_tuple(6, "subFolder4", 2)); list.push_back(std::make_tuple(7, "subFolder5", 5)); int x, y; int k = 0; pt::ptree mainRootNode; for (int i=0; i < list.size(); i++) { if (std::get<2>(list[i])) { continue; } k = 0; pt::ptree subMainRootNode; subMainRootNode.add("id", std::get<0>(list[i])); subMainRootNode.add("value", std::get<1>(list[i])); pt::ptree Node; y = x = std::get<0>(list[i]); int saved_place = 0; for (int j = 0; j < list.size(); j++) { if (x == std::get<2>(list[j])) { k++; std::string str; for(int m = 0;m < k; m++) { str.append("data."); } pt::ptree child; std::string id = str + "id"; std::string value = str + "value"; subMainRootNode.add(id, std::get<0>(list[j])); subMainRootNode.add(value, std::get<1>(list[j])); x = std::get<0>(list[j]); if (!saved_place) { saved_place = j; } } if (((j+1) == list.size()) && saved_place) { j = saved_place ; k = 0; saved_place = 0; x = y; } } mainRootNode.add_child("data", subMainRootNode); pt::write_json(std::cout, subMainRootNode); }}