I'm building a binary tree in PHP. Everything looking good so far but now I'm getting a problem. Node that I placed on right side is showing at left side when we placed right node before left. System looking good if we place left node first and right node after it. Here is the strucure of my php array in json format:
[{"id":"158","parent_id":"157","side":"right","username":"okamikid1"},{"id":"160","parent_id":"157","side":"left","username":"okamikid2"}]
and I am using below function to make it a hierarchy view.
function tree($elements) {
foreach ($elements as $row) {
$row['children'] = array();
$vn = "row" . $row['id'];
${$vn} = $row;
if(!is_null($row['parent_id'])) {
$vp = "parent" . $row['parent_id'];
if(isset($data[$row['parent_id']])) {
${$vp} = $data[$row['parent_id']];
}
else {
${$vp} = array('id' => $row['parent_id'], 'username' => $row['username'], 'parent_id' => null, 'children' => array());
$data[$row['parent_id']] = &${$vp};
}
${$vp}['children'][] = &${$vn};
$data[$row['parent_id']] = ${$vp};
}
$data[$row['id']] = &${$vn};
}
return array_filter($data, function($elem) { return is_null($elem['parent_id']); });
}
Above function producing this output:
{"157":{"id":"157","username":"okamikid1","parent_id":null,"children":[{"id":"158","parent_id":"157","username":"okamikid1","children":[]},{"id":"160","parent_id":"157","username":"okamikid2","children":[]}]}}
Please help me with tree
function and let me know how can I show node on their respective side? Really thanks for your help.