displaying tree info

Statement

given an item which has a parent of itself, its possible to make this into a hierarchical object format and diplay it using a combination of ul / li.

I’ve developed this in both C# and cakephp (See overleaf), and now in 2015 using Yii (without the Set class).

C#

Given a parentid, a flat List<T> can be loaded hierarchically using FindAll / ForEach and AddRange.

Displaying can be done with a combination of ul / li calling a recursive function.

//Flat list to deep one.
var list = GetFlatItems();
foreach (var item in list)
{
  var children = list.FindAll(x => x.Parent == item.Id);
  children.ForEach(x => x.Parent = item);
  item.Children.AddRange(children);
}
roots = list.FindAll(x => x.Children.Count > 0 && x.Parent == null);

//roots is now Top-level parent items
//In the page, just add a ul like so:
//    <ul id="ItemsCtl" runat="server" />
foreach (var item in roots)
{
  AddItem(item, ItemsCtl);
}

private void AddItem(Info item, HtmlGenericControl parent)
{
  var info = new Literal { Text = item.Name };
  var div = new HtmlGenericControl("li") { ID = "d" };
  div.Controls.Add(img); div.Controls.Add(info);
  parent.Controls.Add(div);
  if (item.Children.Count > 0)
  {
    var ul = new HtmlGenericControl("ul") { ID = "u" };
    parent.Controls.Add(ul);
    foreach (var e in item.Children) AddItem(e, ul);
  }
}

php
Developed in Cakephp, Set is a library used for manipulation of arrays. Data can be seen overleaf.

//Controller
$res = $this->Item->find('all');
$res = Set::combine($res, '{n}.Item.id', '{n}.Item.name', '{n}.Skill.parent_id');
$this->set('items', $res);

//View (inside a ul tag).
foreach ($items[0] as $key=>$itm) show($items, $key, $itm);
function show($a, $ky, $itm)
{
  echo "<li>" . $itm . "</li>";
  if (array_key_exists($ky, $a))
  {
    echo "<ul>";
    foreach ($a[$ky] as $key=>$itm) show($a, $key, $itm);
    echo "</ul>";
  }
}

php data
Categories and subcategories of topics. array[1] is the children of item 1 which is a root item (parent 0)

Array
(
    [0] => Array
        (
            [1] => .net
            [7] => java
        )

    [1] => Array
        (
            [2] => ado.net
            [3] => generics
            [4] => asp.net
            [5] => silverlight
            [6] => authentication
        )

)

Leave a Comment