Skip to content

Instantly share code, notes, and snippets.

@heffcodex
Created October 27, 2018 20:44
Show Gist options
  • Save heffcodex/4a52f21c80951c4d835a451965ffb360 to your computer and use it in GitHub Desktop.
Save heffcodex/4a52f21c80951c4d835a451965ffb360 to your computer and use it in GitHub Desktop.
Converts flat array into tree, avoiding the necromancy with references in PHP
<?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;
}
}
<?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