<?php
$list = json_decode(<<<'JSON'
[
{ "TagId": 2, "ParentTagId": null, "Name": "women" },
{ "TagId": 5, "ParentTagId": 2, "Name": "bottom" },
{ "TagId": 4, "ParentTagId": 2, "Name": "top" },
{ "TagId": 7, "ParentTagId": 4, "Name": "shirt" },
{ "TagId": 8, "ParentTagId": 4, "Name": "tshirt" },
{ "TagId": 12, "ParentTagId": 7, "Name": "longsleeve" },
{ "TagId": 16, "ParentTagId": null, "Name": "men" }
]
JSON
);
class Trie implements getIterator
{
protected $parent;
protected $children = [];
public function insert(Node $node)
{
$node->parent = $this;
$this->children[] = $node;
}
public function findById($id)
{
foreach($this->children as $childNode) {
if ($childNode->TagId === $id) {
return $childNode;
}
}
}
public function hasChildren()
{
return (bool) count($this->children);
}
public function getIterator()
{
return $this->children;
}
}
class Node extends Trie
{
public function __construct(stdClass $obj)
{
foreach($obj as $p => $v) {
$this->$p = $v;
}
}
}
$trie = new Trie;
/* Insert all of the parentless nodes */
foreach($list as $n => $obj) {
if (!$obj->ParentTagId) {
$trie->insert(new Node($obj));
unset($list[$n]);
}
}
/* Insert all of the child nodes */
foreach($list as $n => $obj) {
$p = $trie->findById($obj->ParentTagId);
if ($p) {
$p->insert(new Node($obj));
unset($list[$n]);
}
}
var_dump(json_encode($trie));
preferences:
52.96 ms | 402 KiB | 5 Q