您的目標是對具有不同鍵集的多維數組中特定鍵關聯的值求和。考慮以下輸入:
Array ( [0] => Array ( [gozhi] => 2 [uzorong] => 1 [ngangla] => 4 [langthel] => 5 ) [1] => Array ( [gozhi] => 5 [uzorong] => 0 [ngangla] => 3 [langthel] => 2 ) [2] => Array ( [gozhi] => 3 [uzorong] => 0 [ngangla] => 1 [langthel] => 3 ) )
期望的結果是:
Array ( [gozhi] => 10 [uzorong] => 1 [ngangla] => 8 [langthel] => 10 )
要實現這一點,請考慮以下方法:
$final = array(); array_walk_recursive($input, function($item, $key) use (&$final){ $final[$key] = isset($final[$key]) ? $item + $final[$key] : $item; });
array_sum(array_column($input, 'gozhi'));
$final = array_shift($input); foreach ($final as $key => &$value){ $value += array_sum(array_column($input, $key)); } unset($value);
$final = array(); foreach($input as $value) $final = array_merge($final, $value); foreach($final as $key => &$value) $value = array_sum(array_column($input, $key)); unset($value);
以上是如何對多維 PHP 數組中的列值求和?的詳細內容。更多資訊請關注PHP中文網其他相關文章!