Skip to content

Instantly share code, notes, and snippets.

@anver
Created August 1, 2018 05:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anver/418a54cc70fab0135f9497253aabb48e to your computer and use it in GitHub Desktop.
Save anver/418a54cc70fab0135f9497253aabb48e to your computer and use it in GitHub Desktop.
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