473,748 Members | 2,502 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Storing a Hierarchy in an Array

Hello all,

Okay, I am having some troubles. What I am doing here is dealing with
an employee hierarchy that is stored in an array. It looks like this:

$employees = array( "user_id" => array( "name", "title",
"reports to user id", "start date in the format: mm/dd/yyyy" )
);

How can I display this hierarchy in simple nested <li> tags in the most
efficient way possible? I realize that the way this is setup, the
hierarchy is essentially a tree. But I am at a loss as to how to pull
this data out, sort it, and display it wit nested <li> tags. I am
thinking that this is more of a computer science problem....

What I mean by displayed as a hierarchy, is that the nested <li> tags
will indent themselves to look like that. Like this:

- CEO
-- Manager
--- Manager's secretary
--- Minion
-- Manager
That sort of thing. I am just lost as to how I can analyze the
structure of the array and turn it in to output like that.

Any help is greatly appreciated.

Jul 17 '05 #1
8 3480
vc*******@gmail .com wrote:
[snip]
How can I display this hierarchy in simple nested <li> tags in the most
efficient way possible?

[snip]

<?php
echo "<ul>";
foreach($employ ees as $key => $value) {
echo "<li>" . $key . "</li>";
echo "<ul>";
foreach($value as $value2) {
echo "<li>" . $value2 . "</li>";
}
echo "</ul>";
}
echo "</ul>";
?>

Would look like this:

user_id
name
title
reports to user id
start date in the format: mm/dd/yyyy
another user_id
another name
another title
another reports to user id
another start date in the format: mm/dd/yyyy

....and so on.

Zilla
Jul 17 '05 #2
> $employees = array( "user_id" => array( "name", "title",
"reports to user id", "start date in the format: mm/dd/yyyy" )
);
How can I display this hierarchy in simple nested <li> tags in the most
efficient way possible? I realize that the way this is setup, the
hierarchy is essentially a tree. But I am at a loss as to how to pull
this data out, sort it, and display it wit nested <li> tags. I am
thinking that this is more of a computer science problem....

What I mean by displayed as a hierarchy, is that the nested <li> tags
will indent themselves to look like that. Like this:

- CEO
-- Manager
--- Manager's secretary
--- Minion
-- Manager
That sort of thing. I am just lost as to how I can analyze the
structure of the array and turn it in to output like that.


What I see is that the data is not really designed so well in the array
in the first place. You may try and organize it better for what you are
doing. What I mean by this, is that the data is organized is such a
form that all the CEO's are in one part of the array and the mangagers
are under them etc etc.

The next thing is you should be using a recursive function.

Mike
Jul 17 '05 #3
> Would look like this:

user_id
name
title
reports to user id
start date in the format: mm/dd/yyyy
another user_id
another name
another title
another reports to user id
another start date in the format: mm/dd/yyyy


Hmmm maybe I missed the point on my reply lol!

Mike
Jul 17 '05 #4
No... you're right. Let's say we have this stored in the array,
conceptually:

A reports to B.
B reports to C.
D Reports to C.
E Reports to C.
C Reports to Z
G Reports to Z.

The data has to be formatted like this:

CEO Z
- Person C
-- Person B
--- Person A
-- Person D
-- Person E
- Person G

Each dash (-) should be understood as a tab, and a different bulleted
symbol. This is essentially what I mean. The data can't just be
outputted linearly. The LI tags have to be nested, so as to create the
visual hierarchy.... this is why I am finding it so difficult. The
data structure doesn't really allow for this.

Jul 17 '05 #5
vc*******@gmail .com wrote:
No... you're right. Let's say we have this stored in the array,
conceptually:

A reports to B.
B reports to C.
D Reports to C.
E Reports to C.
C Reports to Z
G Reports to Z.

The data has to be formatted like this:

CEO Z
- Person C
-- Person B
--- Person A
-- Person D
-- Person E
- Person G


Sounds like a tree data structure to me. Searching for array
implementation of tree and traversing algorithms might help.

--
<?php echo 'Just another PHP saint'; ?>
Email: rrjanbiah-at-Y!com Blog: http://rajeshanbiah.blogspot.com/

Jul 17 '05 #6
vc*******@gmail .com wrote:
A reports to B.
B reports to C.
D Reports to C.
E Reports to C.
C Reports to Z
G Reports to Z.


Oh like that.... then my example doesn't work.... i will think about it
and maybe give a reply later... have to work now...

Zilla
Jul 17 '05 #7
On 15 May 2005 01:20:21 -0700, "R. Rajesh Jeba Anbiah"
<ng**********@r ediffmail.com> wrote:
vc*******@gmai l.com wrote:
Sounds like a tree data structure to me. Searching for array
implementati on 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($user Id,$name,$title ,$startDate)
{
$this->m_userId = $userId;
$this->m_name = $name;
$this->m_title = $title;
$this->m_startDate = $startDate;
}
function addSubordinate( $item)
{
$this->m_subordinat es[] = $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>Minio n</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_subordinat es[0]->addSubordinate (new
cEmployee('','' ,'Managers Secretary','')) ;
$employeelist->m_subordinat es[0]->addSubordinate (new
cEmployee('','' ,'Minion',''));
$employeelist->addSubordinate (new cEmployee('','' ,'Manager','')) ;
traverse($emplo yeelist);

Have fun. :-)
Jul 17 '05 #8
> How can I display this hierarchy in simple nested <li> tags in the most
efficient way possible?


Now I have had the time to look at your problem. Here is what I came up
with. Remember that the CEO(s) should report to themselves or else it
wont work (look at id 1 and 2 which are CEOs).

I used this array to test with:

$employees = array(1 => array("name1", "title1", 1, "date1"),
2 => array("name2", "title2", 2, "date2"),
33 => array("name3", "title3", 15, "date3"),
15 => array("name4", "title4", 10, "date4"),
10 => array("name5", "title5", 1, "date5"),
37 => array("name6", "title6", 15, "date6"),
40 => array("name7", "title7", 33, "date7"),
45 => array("name8", "title8", 10, "date8"),
50 => array("name9", "title9", 37, "date9"),
4 => array("name10", "title10", 2, "date10"),
7 => array("name11", "title11", 23, "date11"),
456 => array("name12", "title12", 50, "date12"),
89 => array("name13", "title13", 4, "date13"),
23 => array("name14", "title14", 25, "date14"),
57 => array("name15", "title15", 45, "date15"),
25 => array("name16", "title16", 4, "date16")
);

And here's the code:

<?php
//builds an array of relations in format the id1_id2 where
//id2 reports to id1
foreach($employ ees as $key => $value) {
if($value[2] != $key) {
$relations[] = $value[2] . "_" . $key;
}
}
//sort the array in a natural order
natsort($relati ons);
//this function builds an array with flat tree structures
//in the format id1_id2_id3_id4 _....idx
function make_tree_struc ture($array) {
$array2 = $array;
$i = 0;
while(list($key , $value) = each($array)) {
$explode = explode("_", $value);
$n = count($explode) ;
$n = $n - 1;
$under = $explode[$n];
while(list($key 2, $value2) = each($array2)) {
if($key != $key2) {
$explode2 = explode("_", $value2);
$n2 = count($explode2 ) - 1;
$under2 = "";
while($n2 > 0) {
$under2 = $explode2[$n2] . "_" . $under2;
$n2--;
}
$under2 = substr($under2, 0, -1);
$over2 = $explode2[0];
if($over2 == $under) {
$newarray[] = $value . "_" . $under2;
$i = 1;
$x = 1;
unset($array[$key2]);
unset($array2[$key2]);
}
}
}
if($i == 1) {
unset($array[$key]);
unset($array2[$key]);
$i = 0;
}
reset($array2);
}
foreach($array as $value) {
$newarray[] = $value;
}
natsort($newarr ay);
if($x == 1) {
$newarray = make_tree_struc ture($newarray) ;
} else {
$newarray = $array;
}
return $newarray;
}
$flat_tree_stru cture = make_tree_struc ture($relations );
//builds a multidimensiona l array from the flat structures
function build_multidime nsional_array($ array) {
foreach($array as $value) {
$explode = explode("_", $value);
$string = "";
foreach($explod e as $value2) {
$string = $string . "[" . $value2 . "]";
}
$string = "\$newarray " . $string . " = 0;";
eval($string);
}
return $newarray;
}
$tree_structure = build_multidime nsional_array($ flat_tree_struc ture);
//loops over the multidimensiona l array and outputs nested lists
function output_nested_l ists($array, $employees) {
foreach($array as $key => $value) {
echo "<ul>\n";
echo "<li>" . $employees[$key][1] . "</li>\n"; //You
could change this...
if(is_array($va lue)) {
output_nested_l ists($value, $employees);
}
echo "</ul>\n";
}
}
output_nested_l ists($tree_stru cture, $employees);
?>

Outputs this with the example employees array:

* title1
o title5
+ title4
# title3
* title7
# title6
* title9
o title12
+ title8
# title15
* title2
o title10
+ title16
# title14
* title11
+ title13

If you want the name to be written just use $employees[$key][0] where I
wrote "//You could change this".

Zilla.
Jul 17 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1662
by: William Djaja Tjokroaminata | last post by:
Hi, As I am interfacing my code in C++ with a scripting language which is written in C, I need to store pointers to objects in a class hierarchy: ParentClass *obj1; obj1 = new ParentClass (...); ... do things with obj1... STORE_POINTER (scriptObj1, obj1);
15
2337
by: Tor Erik Sønvisen | last post by:
Hi I need a time and space efficient way of storing up to 6 million bits. Time efficency is more important then space efficency as I'm going to do searches through the bit-set. regards tores
0
914
by: rSmoke | last post by:
I'm doing some reflection with VB.NET. I have a 3 level inheritance hierarchy (2 abstract classes and 1 concrete) with a bunch of protected fields in the middle (2nd level abstract) class. When I try to get an array of the FieldInfo objects for each field in the concrete class I am returned only 1 FieldInfo, which is the ONLY field declared at the 1st level of my inheritance hierarchy (1st abstract class). Why doesn't the reflection pull...
3
2338
by: Brad | last post by:
I am storing an array which contains about a dozen chracter items to a Session variable. Later, I need to use this array so I am doing the following: Dim eventTypes As String() = DirectCast(Session("EventTypes"), String()) If Date.Today <= closeDate Then If eventTypes(cblEntries.SelectedIndex) = "J" Then thisFee = Session("JRFee") Else thisFee = Session("PEFee") Else If eventTypes(cblEntries.SelectedIndex) = "J" Then thisFee =
6
3182
by: Kyle Teague | last post by:
What would give better performance, serializing a multidimensional array and storing it in a single entry in a table or storing each element of the array in a separate table and associating the entries with the entry in the other table? Having a separate table would result in two queries instead of one, but you wouldn't have to deal with the overhead of serializing and unserializing data. -- Kyle
3
1550
by: ArmsTom | last post by:
I was using structures to store information read from a file. That was working fine for me, but then I read that anything stored in a structure is added to the stack and not the heap. So, I made a class that stores the same information. The user selects any number of records from the file when the program loads & can then make changes. The records the user selects are added to an array and changes are made to the records in that array...
20
4646
by: Martin Jørgensen | last post by:
Hi, I'm reading a number of double values from a file. It's a 2D-array: 1 2 3 4 5 6 7 ------------- 1 3.2 2 0 2.1 3 9.3 4
10
2307
by: deciacco | last post by:
I'm writing a command line utility to move some files. I'm dealing with thousands of files and I was wondering if anyone had any suggestions. This is what I have currently: $arrayVirtualFile = array( 'filename'=>'filename', 'basename'=>'filename.ext', 'extension'=>'ext', 'size'=>0,
3
1684
by: Ramon F Herrera | last post by:
Newbie alert: I come from C programming, so I still have that frame of mind, but I am trying to "Think in C++". In C this problem would be solved using unions. Hello: Please consider the snippet below. I have some objects which are derived (subclassed?, subtyped?) from simpler ones, in increasing size. There is a linear hierarchy. I need to keep them all in some sort of linked list (perhaps std::vector). I could have several
0
8987
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8826
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9534
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
6793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4867
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3303
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.