[34] => Array
(
[sum] => 13
[name] => 油区开发部
[id] => 27
[parentid] => 1
[children] => Array
(
)
)
[35] => Array
(
[sum] => 2
[name] => 三分公司
[id] => 31
[parentid] => 1
[children] => Array
(
[0] => Array
(
[sum] => 156
[name] => 项目管理分中心
[id] => 52
[parentid] => 31
[children] => Array
(
)
)
[1] => Array
(
[sum] => 12
[name] => 弯管机组
[id] => 54
[parentid] => 31
[children] => Array
(
)
)
[2] => Array
(
[sum] => 20
[name] => 车队
[id] => 53
[parentid] => 31
[children] => Array
(
)
)
[3] => Array
(
[sum] => 10
[name] => 维修机组
[id] => 55
[parentid] => 31
[children] => Array
(
)
)
[4] => Array
(
[sum] => 55
[name] => 机关
[id] => 51
[parentid] => 31
[children] => Array
(
)
)
)
)
[36] => Array
(
[sum] => 56
[name] => 五分公司
[id] => 32
[parentid] => 1
[children] => Array
(
)
)
如何计算三分公司的sum值,是三分公司 children下的 所有 sum的和
5 回答
哔哔one
TA贡献1854条经验 获得超8个赞
$data = Array
(
34 => Array
(
'sum' => 13,
'name' => '油区开发部',
'id' => 27,
'parentid'=> 1,
'children' => Array
(
),
),
35 => Array(
'sum' => 2,
'name' => '三分公司',
'id' => 31,
'parentid'=> 1,
'children' => Array
(
0 => Array
(
'sum' => 156,
'name' => '项目管理分中心',
'id' => 52,
'parentid'=> 31,
'children'=> [],
),
1 => Array
(
'sum' => 12,
'name' => '弯管机组',
'id' => 54,
'parentid'=> 31,
'children'=> [],
),
),
),
36 => Array
(
'sum' => 56,
'name' => '五分公司',
'id' => 32,
'parentid'=> 1,
'children' => Array
(
),
)
);
foreach($data as $key => $value)
{
$data[$key]['sum'] = array_sum(array_column($value['children'],'sum'));
}
print_r($data);
森栏
TA贡献1810条经验 获得超5个赞
$arr = [[
'name' => '三分公司',
'children' => [
['sum' => 156],
['sum' => 12]
]
]];
function getChildrenSum($children)
{
$sum = 0;
if (is_array($children)) {
foreach ($children as $item) {
$sum += $item['sum'];
if(isset($item['children'])){
$sum += getChildrenSum($item['children']);
}
}
}
return $sum;
}
$sum = array_reduce(
array_filter($arr, function ($item) {
return $item['name'] === '三分公司';
}),
function ($sum, $item) {
return $sum + getChildrenSum($item['children']);
},
0
);
echo $sum;
DIEA
TA贡献1820条经验 获得超2个赞
定义一个变量:$sums = 0;
假设你外面的大数组是 $data,
foreach($data as $key => $value)
{
if($value['name'] == '三分公司'){
foreach($value['children'] as $k => $v)
{
$sums += $v['sum']
}
}
}
print_r($sums);
或者是:
foreach($data as $key => $value)
{
$sums = array_sum(array_column($value['children'],'sum'));
}
print_r($sums);
- 5 回答
- 0 关注
- 1289 浏览
添加回答
举报
0/150
提交
取消