我写了recurie,显示了树。
结构数据库是:
id | name | value | children
1 Auto 1 [2,3,5]
我从Db获取所有行,然后传递给函数getValuesParametersByID()
:
public function getValuesParametersByID($data = array(), $additional_parameters = array())
{
foreach ($data as $k => $value) {
if (is_array($value['children']) && count($value['children']) > 0) {
$id = (string)$value["_id"];
$list[] = ['id' => $id, 'title' => $value["name"], "value" => $value["value"]];
$list[]['nodes'] = $this->getChildren($all, $value['children']);
} else {
$id = (string)$value["_id"];
$list[] = ['id' => $id, 'title' => $value["name"], "value" => $value["value"], 'nodes' => []];
}
}
return $list;
}
private function getChildren($all, $childs)
{
$list = [];
foreach ($childs as $k => $child) {
if (is_array($all[$child]['children'])) {
$children_short = $all[$child];
$tmpArray = ["title" => $children_short["name"], "value" => $children_short["value"]];
$tmpArray['nodes'] = $this->getChildren($all, $all[$child]['children']);
} else {
$tmpArray = $all[$child];
}
$list[] = $tmpArray;
}
return $list;
}
有时它不会添加到节点字段:id, title, value.
您可以在JSON格式中看到函数的结果:
http://www.jsoneditoronline.org/?id=1313e47e7cccaac3095cabee9313005a
您可以看到数组的第二个元素只有一个nodes
字段。
我认为,这部分代码存在问题:
} else {
$tmpArray = $all[$child];
}