Created
October 27, 2018 20:44
-
-
Save heffcodex/4a52f21c80951c4d835a451965ffb360 to your computer and use it in GitHub Desktop.
Converts flat array into tree, avoiding the necromancy with references in PHP
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
<?php | |
class Array2Tree | |
{ | |
public static function convert(array $data) | |
{ | |
$instance = new self($data); | |
return $instance->getTree(); | |
} | |
public function getTree() | |
{ | |
$this->makeObjects(); | |
$this->buildObjectTree(); | |
return $this->toArray($this->root->child); | |
} | |
private function __construct(array $data) | |
{ | |
$this->data = $data; | |
$this->objs = []; | |
$this->root = new stdClass(); | |
} | |
private function makeObjects() | |
{ | |
foreach ($this->data as $item) { | |
$this->objs[$item['id']] = new stdClass(); | |
// Define your own fields here: | |
$this->objs[$item['id']]->id = $item['id']; | |
$this->objs[$item['id']]->parent = $item['parent']; | |
$this->objs[$item['id']]->name = $item['name']; | |
// ... | |
} | |
} | |
private function buildObjectTree() | |
{ | |
foreach ($this->objs as &$item) { | |
if ($item->parent && isset($this->objs[$item->parent])) { | |
$this->objs[$item->parent]->child[$item->id] = $item; | |
} else { | |
$this->root->child[$item->id] = $item; | |
} | |
} | |
} | |
private function toArray($data) | |
{ | |
if (is_object($data)) { | |
$data = get_object_vars($data); | |
} | |
if (is_array($data)) { | |
$data = array_map([$this, __FUNCTION__], $data); | |
} | |
return $data; | |
} | |
} |
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
<?php | |
$data = [ | |
[ | |
'id' => '1', | |
'parent' => NULL, | |
'name' => 'This will be in root', | |
], | |
[ | |
'id' => '2', | |
'parent' => '1', | |
'name' => 'This will be nested', | |
], | |
[ | |
'id' => '3', | |
'parent' => '999', | |
'name' => 'This will be in root too, because of invalid parent', | |
], | |
]; | |
$tree = Array2Tree::convert($data); | |
print_r($tree); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment