Created
August 1, 2018 05:36
-
-
Save anver/418a54cc70fab0135f9497253aabb48e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function test_reference_tree_building() { | |
$source = [ | |
1 => ['name' => 'Parent One', 'parent_id' => null], 2 => ['name' => 'Parent Two', 'parent_id' => null], | |
3 => ['name' => 'Child One', 'parent_id' => 1], 4 => ['name' => 'Child Two', 'parent_id' => 1], | |
5 => ['name' => 'Child Three', 'parent_id' => 2], 6 => ['name' => 'Child Four', 'parent_id' => 5], | |
7 => ['name' => 'Child Five', 'parent_id' => 2], 8 => ['name' => 'Child Six', 'parent_id' => 3], | |
9 => ['name' => 'Child Seven', 'parent_id' => 6] | |
]; | |
$nested = []; | |
foreach ( $source as &$s ) { | |
if ( is_null( $s['parent_id'] ) ) { | |
$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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment