Create Array Tree from Array List

create array tree from array list

oke this is how i solved it:

$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['children'] = createTree($list, $list[$l['id']]);
}
$tree[] = $l;
}
return $tree;
}

Make a Tree from List of Array (ResultSet for example)

I DID IT ! OH MY GOD! :D :D :D :D :D :D :D...

private static void finalFillerTotalSuperSpecial(List<String[]> initialList, HashMap<String,Object> mapa){

String[] currentElement = null;
String currentKey = null;

String[] nextElement = null;
String nextKey = null;
int i=0,start,end;

while (i < initialList.size()) {
start = i;

currentElement = initialList.get( i++ );
currentKey = currentElement[0];

if (i<initialList.size()){
nextElement = initialList.get( i );
nextKey = nextElement[0];
}

HashMap<String,Object> insideMap = new HashMap<String,Object>();
mapa.put(currentKey, insideMap);

while (currentKey.equals(nextKey) && i < initialList.size()) {
currentElement = initialList.get( i++ );
currentKey = currentElement[0];

if (i<initialList.size()){
nextElement = initialList.get( i );
nextKey = nextElement[0];
}

}
end = i;

List<String[]> listOfCurrentElements = new ArrayList<String[]>();
for (int j=start;j<end;j++)
listOfCurrentElements.add( getNextArray(initialList.get(j)) );

if ( listOfCurrentElements.get(0).length>1 )
finalFillerTotalSuperSpecial(listOfCurrentElements,insideMap);
else
insideMap.put(listOfCurrentElements.get(0)[0], null);
}



}

Create array tree of nth level form array list

Try like this.

$array = 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')
);

echo '<pre>';
print_r(array_to_tree($array));
exit;

Function to convert tree.

function array_to_tree(array $array, $parent_id = 0)
{
$array = array_combine(array_column($array, 'id'), array_values($array));

foreach ($array as $k => &$v) {
if (isset($array[$v['parentid']])) {
$array[$v['parentid']]['children'][$k] = &$v;
}
unset($v);
}

return array_filter($array, function($v) use ($parent_id) {
return $v['parentid'] == $parent_id;
});
}

Output will be.

Sample Image

As per your requirement you want only 2 levels then don't use recursive function.
//remove createTree from foreach

function createTree(&$list, $parent){
$tree = array();
foreach ($parent as $k=>$l){
if(isset($list[$l['id']])){
$l['children'] = $list[$l['id']]; //remove createTree from here.
}
$tree[] = $l;
}
return $tree;
}

Build a tree from a flat array in PHP

You forgot the unset() in there bro.

function buildTree(array &$elements, $parentId = 0) {
$branch = array();

foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[$element['id']] = $element;
unset($elements[$element['id']]);
}
}
return $branch;
}

Python: create tree structure from given array/list

I didn't see the connection between example input and example output, so I'm going to take a guess at what you want.

Here is an implementation:

# sample input
data = [
['P1', 'P1', 'P1', 'P1', 'P2', 'P2', 'P2'],
['L1', 'L1', 'L1', 'L1', 'L1', 'L2', 'L3'],
['V1', 'V1', 'V2', 'V3', 'V2', 'V1', 'V4'],
['O1', 'O2', 'O1', 'O3', 'O1', 'O2', 'O2']
]

forest = {}
for *path, last in zip(*data):
node = forest
for code in path:
node = node.setdefault(code, {})
node[last] = last

After running this code, forest will be the following nested dictionary:

{
"P1": {
"L1": {
"V1": {
"O1": "O1",
"O2": "O2"
},
"V2": {
"O1": "O1"
},
"V3": {
"O3": "O3"
}
}
},
"P2": {
"L1": {
"V2": {
"O1": "O1"
}
},
"L2": {
"V1": {
"O2": "O2"
}
},
"L3": {
"V4": {
"O2": "O2"
}
}
}
}

Construct N-ary tree from ArrayList in java

Did small modification in addTreeNode and find_parentNode method. Please try below:

public void addTreeNode(Node parent, Node newChild)
{

if(parent==null){
return;
}
if(parent.child == null)
{
parent.child = newChild;
return;
}

Node temp = parent.child;

while(temp.sibling != null)
{
temp = temp.sibling;
}
temp.sibling = newChild;

}


public Node find_parentNode(ArrayList<Node> nodes ,int parentID)
{
for(int i= 0;i<nodes.size();i++)
{
if(nodes.get(i).ID == parentID)
return nodes.get(i);
}

return null;
}

In main method, below is the use case:

    NTree tree = new NTree();
tree.root = new Node("A", 1, 0);
ArrayList<Node> list_nodes = new ArrayList<Node>();
list_nodes.add(tree.root);
list_nodes.add(new Node("B", 2, 1));
list_nodes.add(new Node("C", 3, 1));
list_nodes.add(new Node("D", 4, 1));
list_nodes.add(new Node("E", 5, 3));
list_nodes.add(new Node("F", 6, 3));

for (int i = 0; i < list_nodes.size(); i++) {
Node parent = tree.find_parentNode(list_nodes, list_nodes.get(i).parentID);
tree.addTreeNode(parent, list_nodes.get(i));
}
tree.preorder(tree.root);

How to build grouped tree array from flat array in php

function buildTree(array $flat)
{
$grouped = [];
foreach ($flat as $node) {
$grouped[$node['parent_id']][] = $node;
}

$fnBuilder = function ($siblings) use (&$fnBuilder, $grouped) {
foreach ($siblings as $k => $sibling) {
$id = $sibling['id'];
if (isset($grouped[$id])) {
$sibling['children'] = $fnBuilder($grouped[$id]);
}
$siblings[$k] = $sibling;
}
return $siblings;
};
return $fnBuilder($grouped[0]);
}


$tree = buildTree($flat);

pass tree structure array to groupedTree();

$groupd = groupedTree($tree);

echo json_encode($groupd, JSON_PRETTY_PRINT);


function groupedTree($tree)
{
$groupedByFuncTableName = array_reduce($tree, function (array $accumulator, array $element) {
if (isset($element['children'])) {
$element['children'] = groupedTree($element['children']);
}
$accumulator[$element['name']][] = $element;

return $accumulator;
}, []);
return $groupedByFuncTableName;
}

Build tree array from flat array in javascript

There is an efficient solution if you use a map-lookup. If the parents always come before their children you can merge the two for-loops. It supports multiple roots. It gives an error on dangling branches, but can be modified to ignore them. It doesn't require a 3rd-party library. It's, as far as I can tell, the fastest solution.

function list_to_tree(list) {
var map = {}, node, roots = [], i;

for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i; // initialize the map
list[i].children = []; // initialize the children
}

for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parentId !== "0") {
// if you have dangling branches check that map[node.parentId] exists
list[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}

var entries = [{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1",
"children": null
},
{
"id": "6",
"parentId": "12",
"text": "Boy",
"level": "2",
"children": null
},
{
"id": "7",
"parentId": "12",
"text": "Other",
"level": "2",
"children": null
},
{
"id": "9",
"parentId": "0",
"text": "Woman",
"level": "1",
"children": null
},
{
"id": "11",
"parentId": "9",
"text": "Girl",
"level": "2",
"children": null
}
];

console.log(list_to_tree(entries));

Build a list tree with an array

You really need a recursive function to build this tree. Here is one that will do what you want. Note that it takes account of the extra (unnecessary?) array layer that you have in your input data, if that doesn't actually exist remove the [0] from the reference to $lists in the function:

function make_list($lists, $parent = 0) {
$children = array_filter($lists[0], function ($v) use($parent) { return $v['parent'] == $parent; });
if (!count($children)) return;
echo "<ul>\n";
foreach ($children as $child) {
echo "<li>{$child['name']}</li>\n";
make_list($lists, $child['id']);
}
echo "</ul>\n";
}

make_list($lists);

Output:

<ul>
<li>Menu 1</li>
<ul>
<li>Menu 2</li>
<ul>
<li>Menu 3</li>
</ul>
<li>Menu 4</li>
</ul>
<li>Menu 5</li>
</ul>

Demo on 3v4l.org



Related Topics



Leave a reply



Submit