Example data
Imagine that we have an array like this one:
$data = array( '1' => array( 'label' => "A", 'father' => '' ), '2' => array( 'label' => "B", 'father' => '' ), '3' => array( 'label' => "C", 'father' => '' ), '4' => array( 'label' => "D", 'father' => '' ), '5' => array( 'label' => "one", 'father' => '1' ), '6' => array( 'label' => "two", 'father' => '1' ), '7' => array( 'label' => "three", 'father' => '1' ), '8' => array( 'label' => "node 1", 'father' => '2' ), '9' => array( 'label' => "node 2", 'father' => '2' ), '10' => array( 'label' => "node 3", 'father' => '2' ), '11' => array( 'label' => "I", 'father' => '9' ), '12' => array( 'label' => "II", 'father' => '9' ), '13' => array( 'label' => "III", 'father' => '9' ), '14' => array( 'label' => "IV", 'father' => '9' ), '15' => array( 'label' => "V", 'father' => '9' ), );
As you can see this is the typical situation you can encounter after extracting a table from a database. The keys of the array are the taken from the id column of the database and the values of each array rapresent other columns.
The function to convert flat array to nested
After tested many solutions, I’ve found out this one:
function array_totree( &$a, $parent_key, $children_key='children' ) { $orphans = true; $i; while( $orphans ) { $orphans = false; foreach( $a as $k=>$v ) { // is there $a[$k] sons? $sons = false; foreach( $a as $x=>$y ) { if( $y[$parent_key]!=false and $y[$parent_key]==$k ) { $sons=true; $orphans=true; break; } } // $a[$k] is a son, without children, so i can move it if( !$sons and $v[$parent_key]!=false ) { $a[$v[$parent_key]][$children_key][$k] = $v; unset( $a[$k] ); } } } }
Arguments
This function accepts three arguments:
-
ARRAY $array
The input array that we want to order. The array is passed by reference
-
STRING $parent_key
The associative key used to define the father id of a node inside the node itself
-
STRING $children_key
The associative key that will be created by the function and that will be rapresent the children of the new multi dimensional array
Return
The function returns nothing.
Usage
Let’s assume we are using the $data array defined above. So we can apply the function that way:
array_totree( $data, 'father', 'children' );
The output
Now the $data array looks like:
- A
- one
- two
- three
- B
- node 1
- node 3
- node 2
- I
- II
- III
- IV
- V
- C
- D
The complete script
You can download the whole script (that include the example also) just clicking the button below.
Download the Function + Example
Hope this helps
I hope you have used found useful my solution.
If you have encountered some problems, please let me know.
If you have a smarter solution to convert flat array to nested please add a comment below.
Bye!