2 回答

TA貢獻1824條經驗 獲得超5個贊
您可以只映射主數組并推送其元素的總和:
$array['main'] = array_map(static function($counts) {
$sum = ctype_digit(implode('', $counts)) ? array_sum($counts) : '-';
return array_merge($counts, [$sum]);
}, $array['main']);
密鑰的值main將是您實際需要的:
array(2) {
["firstYearStudents"]=>
array(3) {
[0] => int(10)
[1] => int(12)
[2] => int(22)
}
["secondYearStudents"]=>
array(3) {
[0] => int(8)
[1] => int(9)
[2] => int(17)
}
["programCode"]=>
array(3) {
[0] => string(8) "03.02.01"
[1] => string(8) "03.01.01"
[2] => string(1) "-"
}
}

TA貢獻1847條經驗 獲得超11個贊
如果您只需要移動這兩個屬性,這應該是一個簡單的解決方案:
$data = [
'main' => [
'firstYearStudents' => [
'10',
'12'
],
'secondYearStudents' => [
'8',
'9'
]
],
'total' => [
'totalFirstYear' => '22',
'totalSecondYear' => '17'
]
];
$data['main']['firstYearStudents'][] = $data['total']['totalFirstYear'];
$data['main']['secondYearStudents'][] = $data['total']['totalSecondYear'];
如有必要,您應該能夠擴展它以涵蓋更多年,或者最終編寫一個循環來管理您需要的年數。
- 2 回答
- 0 關注
- 193 瀏覽
添加回答
舉報