求助:计算多维数组各列数值总和并找出最大值
Hey there! Let's tackle this problem step by step. Your array has a mix of indexed and associative rows, with varying column counts and even non-continuous column indices—so we need to handle that carefully.
Solution for Calculating Column Sums and Finding the Maximum
First, let's outline the core tasks we need to complete:
- Account for both numeric-indexed and associative columns across all rows
- Sum values for every unique column index across all rows
- Identify the largest sum from those column totals
Here's a PHP implementation that handles all these edge cases:
<?php $a = [[1, 3, 4], [2, 5], [2 => 3, 5 => 8], [1, 1, 5 => 1]]; // Step 1: Gather all unique column indices from every row $uniqueColumns = []; foreach ($a as $row) { foreach (array_keys($row) as $colIndex) { $uniqueColumns[$colIndex] = true; // Use array keys to auto-remove duplicates } } $uniqueColumns = array_keys($uniqueColumns); // Convert to a clean list of indices // Step 2: Calculate the sum for each unique column $columnSums = []; foreach ($uniqueColumns as $col) { $total = 0; foreach ($a as $row) { // Add the value if the column exists in the row, else add 0 $total += isset($row[$col]) ? $row[$col] : 0; } $columnSums[$col] = $total; } // Step 3: Find the maximum sum from all columns $maxColumnSum = max($columnSums); // Optional: Print results to verify echo "Column sums:\n"; print_r($columnSums); echo "\nMaximum column sum: " . $maxColumnSum; ?>
Let's break down how this works:
- Collecting unique columns: We loop through every row, grab all its column keys, and store them in an associative array (this automatically eliminates duplicates). Then we extract the keys to get a clean list of all unique columns (in your case, that's
0, 1, 2, 5). - Calculating column sums: For each unique column index, we loop through every row. If the row has that column, we add its value to the total; if not, we add 0 to keep the sum accurate.
- Finding the maximum: We use PHP's built-in
max()function on the$columnSumsarray to get the largest total quickly.
Example Output:
When you run this code, you'll see:
Column sums: Array ( [0] => 4 [1] => 9 [2] => 7 [5] => 9 ) Maximum column sum: 9
This checks out:
- Column 0: 1 (row 1) + 2 (row 2) + 0 (row 3) + 1 (row 4) = 4
- Column 1: 3 + 5 + 0 + 1 = 9
- Column 2: 4 + 0 + 3 + 0 = 7
- Column 5: 0 + 0 + 8 + 1 = 9
So the maximum sum here is 9, shared by columns 1 and 5.
内容的提问来源于stack exchange,提问作者Tadas Narkevičius
相关产品推荐
相关产品推荐

