PHP实现相同日期数组值求和:视图数大于0时合并同日期值
Solution for Summing Values by Date Based on View Condition
Got it, let's work through this problem directly. Based on your requirements, here's a practical PHP implementation that delivers exactly what you need:
Core Requirements Recap
- If
$viewis less than 1: Return the original array without any changes - If
$viewis greater than 0: Group items by theirdatekey, sum the correspondingvaluevalues, then output the result in your specified indexed array format
Working Code Implementation
// Replace this with your actual input array $originalData = [ ['date' => '09-04-2018', 'value' => 10], ['date' => '09-04-2018', 'value' => 20], ['date' => '10-04-2018', 'value' => 15], ['date' => '10-04-2018', 'value' => 17], ['date' => '11-04-2018', 'value' => 34], ['date' => '12-04-2018', 'value' => 20], ['date' => '12-04-2018', 'value' => 16], ['date' => '13-04-2018', 'value' => 39], ]; $view = 1; // Replace with your actual view value $finalResult = []; // Handle the two conditions if ($view < 1) { // No processing needed—return original array $finalResult = $originalData; } else { // Step 1: Group dates and sum their values $groupedSums = []; foreach ($originalData as $item) { $currentDate = $item['date']; // Initialize sum for new dates if (!isset($groupedSums[$currentDate])) { $groupedSums[$currentDate] = 0; } // Add to the total for this date $groupedSums[$currentDate] += $item['value']; } // Step 2: Convert grouped data to your desired format foreach ($groupedSums as $date => $totalValue) { $finalResult[] = [ 'date' => $date, 'value' => $totalValue ]; } } // Output the result (matches your requested structure) print_r($finalResult);
How This Works
- When
$view < 1: We simply pass the original array through—no extra processing, keeping your raw data intact. - When
$view > 0:- First, we use an associative array to track running totals for each date. This makes summing values quick and efficient.
- Then we convert that associative array back into the indexed array structure you specified, so the output matches your example exactly.
Example Output
When $view = 1, you’ll get this output:
Array ( [0] => Array ( [date] => 09-04-2018 [value] => 30 ) [1] => Array ( [date] => 10-04-2018 [value] => 32 ) [2] => Array ( [date] => 11-04-2018 [value] => 34 ) [3] => Array ( [date] => 12-04-2018 [value] => 36 ) [4] => Array ( [date] => 13-04-2018 [value] => 39 ) )
Just swap out the sample $originalData and $view variable with your actual data, and this code will work seamlessly.
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

