Skip to content

Instantly share code, notes, and snippets.

@amberlex78
Last active August 29, 2015 14:26
Show Gist options
  • Select an option

  • Save amberlex78/6db35d46eea62a74f80f to your computer and use it in GitHub Desktop.

Select an option

Save amberlex78/6db35d46eea62a74f80f to your computer and use it in GitHub Desktop.
Tree::flat2nested($arr);
<?php
/*
-----------------------------------
Reformat flat array to nested array
-----------------------------------
Array(
[2] => Array(
[id] => 2
[parent_id] => 0
[title] => Новости
)
[27] => Array(
[id] => 27
[parent_id] => 2
[title] => www-1
)
[28] => Array(
[id] => 28
[parent_id] => 2
[title] => www-2
)
[3] => Array(
[id] => 3
[parent_id] => 0
[title] => Статьи
)
[29] => Array(
[id] => 29
[parent_id] => 3
[title] => www-3
)
)
Array(
[2] => Array(
[id] => 2
[parent_id] => 0
[title] => Новости
[sub] => Array(
[27] => Array(
[id] => 27
[parent_id] => 2
[title] => www-1
)
[28] => Array(
[id] => 28
[parent_id] => 2
[title] => www-2
)
)
)
[3] => Array(
[id] => 3
[parent_id] => 0
[title] => Статьи
[sub] => Array(
[29] => Array(
[id] => 29
[parent_id] => 3
[title] => www-3
)
)
)
)
*/
/**
* Class Tree
*/
class Tree
{
/**
* Return nested array
* @param array $arr_assoc
* @return array
*/
public static function flat2nested(array $arr_assoc)
{
$nested_array = [];
foreach ($arr_assoc as $id => &$node) {
if (isset($node['parent_id'])) {
if ($node['parent_id'] == 0) {
$nested_array[$id] = &$node;
} else {
$arr_assoc[$node['parent_id']]['sub'][$id] = &$node;
}
}
}
return $nested_array;
}
}
// Usage
//
Tree::flat2nested($arr);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment