You are here: Re: Storing a Hierarchy in an Array « PHP Programming Language « IT news, forums, messages
Re: Storing a Hierarchy in an Array

Posted by Matt on 05/15/05 16:51

On 15 May 2005 01:20:21 -0700, "R. Rajesh Jeba Anbiah"
<ng4rrjanbiah@rediffmail.com> wrote:

>vcardillo@gmail.com wrote:
> Sounds like a tree data structure to me. Searching for array
>implementation of tree and traversing algorithms might help.

I agree that you are probably looking at a tree structure rather than
an array. Personally I would also use classes to encapsulate the
employees (each employee is effectively a node in the tree) i.e:

class cEmployee {
var $m_userId;
var $m_name;
var $m_title;
var $m_startDate;
var $m_subordinates = array();
function cEmployee($userId,$name,$title,$startDate)
{
$this->m_userId = $userId;
$this->m_name = $name;
$this->m_title = $title;
$this->m_startDate = $startDate;
}
function addSubordinate($item)
{
$this->m_subordinates[] = $item;
}
};

To traverse the tree you would need a function along these lines:

function traverse($h)
{
echo "<ul><li>";
echo $h->m_title;
while (list($key, $val) = each($h->m_subordinates))
{
traverse($val);
}
echo "</li></ul>\n";
};

This is not perfect as even employees who have no subordinates are
still an unordered list themselves i.e:

<ul><li>CEO<ul><li>Manager<ul><li>Managers Secretary</li></ul>
<ul><li>Minion</li></ul>
</li></ul>
<ul><li>Manager</li></ul>
</li></ul>

Then there is also the task of populating the tree to begin with. I
will leave that to you. To get the printout above I used the following
code:

$employeelist = new cEmployee('','','CEO','');
$employeelist->addSubordinate(new cEmployee('','','Manager',''));
$employeelist->m_subordinates[0]->addSubordinate(new
cEmployee('','','Managers Secretary',''));
$employeelist->m_subordinates[0]->addSubordinate(new
cEmployee('','','Minion',''));
$employeelist->addSubordinate(new cEmployee('','','Manager',''));
traverse($employeelist);

Have fun. :-)

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация