公司开发一个菜单功能,要求遍历子级,找了半天没有找到合适的 , 于是就复制某人的代码拿过来用了 , 记录一下防止下次找不到 , 真香!!!
$this->buildTree($arrays,0,'parent_id')
public function buildTree($rows, $rootId, $pidKey, $childrenKey = "children")
{
$child = $this->findChild($rows, $rootId, $pidKey);
if (empty($child)) {
return null;
}
foreach ($child as $key => $value) {
$resTree = $this->buildTree($rows, $value['id'], $pidKey, $childrenKey);
if (null != $resTree) {
$child[$key][$childrenKey] = $resTree;
}
}
return $child;
}
private function findChild(&$arr, $id, $pidKey)
{
$child = [];
foreach ($arr as $key => $value) {
if ($value[$pidKey] == $id) {
$child[] = $value;
}
}
return $child;
}