Data Structure, Development, PHP

Data Structure – Creating Tree Data Structure

As per title, this post will give an example how to create a tree data structure using recursive function.

The data structure will be like below illustration:

/A
–/A-1
—-/A-1-a
—-/A-1-b
/B
/C
–/C-1
—-/C-1-c

Below is an implementation based on this post – a folder tree created based on given directory using recursive function.

Data Structure - Tree
Data Structure – Tree

Here are the code:

public function generateTree($value) {
	$list = array();
	if ($handle = opendir($value)) 
	{
		while (false !== ($entry = readdir($handle))) 
		{
			if ($entry != "." && $entry != "..") 
			{	
				if(is_dir($value . '/' .$entry))
				{
					$list[] = array( 
						'text' => $entry, 
						'children' => generateTree($value . '/' .$entry)
					);
				}
				else
				{
					$list[] = pathinfo($entry);
				}
			}
		}
		closedir($handle);
	}
	return $list;
}

Just set the following:

$list = generateTree('path/');

You should get something similar to below when you print_r($list);.

[
	{
		'text':'A',
		'children':
		[
			{
				'text':'A-1',
				'children':
				[
					{
						'text':'A-1-a'
					},
					{
						'text':'A-1-b'
					}
				]
			}
		]
	},
	{
		'text':'B'
	}
	{
		'text':'C',
		'children':
		[
			'text':'C-1',
			'children':
			[
				{
					'text':'C-1-c'
				}
			]
		]
	}
]

Leave a Reply

Your email address will not be published. Required fields are marked *

20 − eighteen =