Creating a nested array from items with parent IDs



In this tutorial I will show you a way of Creating a nested array from items with parent IDs.
This is useful for when you have a website working with multiple categories with parent categories. But it can be applied anywhere, really!

The original array

For this code example, we will suppose we have an array of the following structure:

    [ID] => array(
		'name' => [NAME],
        ... //Other optional variables like description, ... can go here
		'parent_id' => [NULL or NUMERIC PARENT_ID]
	),

With that in mind, this is the array I will be using for this example:

$source = array(
    1 => array(
		'name' => 'Parent One',
		'parent_id' => null
	),
	2 => array(
		'name' => 'Parent Two', 
		'parent_id' => null
	),
	3 => array(
		'name' => 'Child One',
		'parent_id' => 1
	),
	4 => array(
		'name' => 'Child Two', 
		'parent_id' => 1
	),
	5 => array(
		'name' => 'Child Three',
		'parent_id' => 2
	),
	6 => array(
		'name' => 'Child Four',
		'parent_id' => 5
	),
	7 => array(
		'name' => 'Child Five', 
		'parent_id' => 2
	),
	8 => array(
		'name' => 'Child Six',
		'parent_id' => 3
	),
	9 => array(
		'name' => 'Child Seven',
		'parent_id' => 6
	)
);

 Creating a nested array

We can now use the following code for creating a nested array from items with parent IDs.

function makeNested($source) {
	$nested = array();

	foreach ( $source as &$s ) {
		if ( is_null($s['parent_id']) ) {
			// no parent_id so we put it in the root of the array
			$nested[] = &$s;
		}
		else {
			$pid = $s['parent_id'];
			if ( isset($source[$pid]) ) {
				// If the parent ID exists in the source array
				// we add it to the 'children' array of the parent after initializing it.

				if ( !isset($source[$pid]['children']) ) {
					$source[$pid]['children'] = array();
				}

				$source[$pid]['children'][] = &$s;
			}
		}
	}
	return $nested;
}

This function makes use of references to assign the children and store the result in the nested array variable.
Basicly what it does is check if the item has a parent. If it doesn’t have a parent ID it will store it in the root of the array.
Otherwise it will put it into the children variable of the nested array.

The result

As a result, the output of this function would be something like this:



Array
(
    [0] => Array
        (
            [name] => Parent One
            [parent_id] => 
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => Child One
                            [parent_id] => 1
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [name] => Child Six
                                            [parent_id] => 3
                                        )

                                )

                        )

                    [1] => Array
                        (
                            [name] => Child Two
                            [parent_id] => 1
                        )

                )

        )

    [1] => Array
        (
            [name] => Parent Two
            [parent_id] => 
            [children] => Array
                (
                    [0] => Array
                        (
                            [name] => Child Three
                            [parent_id] => 2
                            [children] => Array
                                (
                                    [0] => Array
                                        (
                                            [name] => Child Four
                                            [parent_id] => 5
                                            [children] => Array
                                                (
                                                    [0] => Array
                                                        (
                                                            [name] => Child Seven
                                                            [parent_id] => 6
                                                        )

                                                )

                                        )

                                )

                        )

                    [1] => Array
                        (
                            [name] => Child Five
                            [parent_id] => 2
                        )

                )

        )

)

This code should be easy enough to modify to your own needs.

That’s all, folks!

I hope this small code snippet has been useful. I am certain the theory behind it can also be applied in Java, C, …!

If you liked the article, please feel free to share it on Twitter, Facebook, StumbleUpon, or any other social media of your choice

Share the knowledge!
Share on Facebook3Tweet about this on Twitter185Share on Google+4Share on StumbleUpon314Share on Reddit10Share on LinkedIn0Share on TumblrBuffer this pageDigg this

Comments

You may also like...

x
Stay updated