Skip to content

Instantly share code, notes, and snippets.

@mgsmus
Created March 7, 2018 10:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mgsmus/2e7098822988075b5e3a6a895911a1b8 to your computer and use it in GitHub Desktop.
Save mgsmus/2e7098822988075b5e3a6a895911a1b8 to your computer and use it in GitHub Desktop.
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;
}
/*
$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
)
);
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
)
)
)
)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment