一个小demo---递归计算子类下的某个值的总和

 

public function demo($frames)
{
foreach ($frames as $k => $frame) {
$frames[$k]['allCount'] = $frame['employeeCount'];
if ($frame['children']) {
$frames[$k]['children'] = $this->demo($frame['children']);
$frames[$k]['allCount'] += array_sum(array_column($frames[$k]['children'],'allCount'));
}
}

return $frames;
}
public function index()
{
$arr = [[
'id'=>1,
'name'=>'就是',
'employeeCount'=>10,
'children'=>[[
'id'=>1,
'name'=>'就是1',
'employeeCount'=>6,
'children'=>[[
'id'=>1,
'name'=>'就是2',
'employeeCount'=>4,
'children'=>[
],
]],
'id'=>2,
'name'=>'就是3',
'employeeCount'=>11,
'children'=>[[
'id'=>1,
'name'=>'就是3',
'employeeCount'=>0,
'children'=>[[
'id'=>1,
'name'=>'就是4',
'employeeCount'=>2,
'children'=>[[
'id'=>1,
'name'=>'就是21',
'employeeCount'=>4,
'children'=>[
],
]],
]],
]],
]],

]];
$res = $this->demo($arr);dd($res);

posted @ 2019-05-31 11:21  迷失在路上  阅读(219)  评论(0编辑  收藏  举报