John Davidson

php - Total Result by Column and Date

0 comments
Message:


I have a table similar to this example.

































id s_id date
X 8 2022-03-23
X 9 2022-03-24
X 9 2022-03-24
X 10 2022-03-24


My Answer:
To calculate the total result by column and date in PHP, you can use the following code:

php

// Sample data
$data = [
['id' => 'X', 's_id' => 8, 'date' => '2022-03-23'],
['id' => 'X', 's_id' => 9, 'date' => '2022-03-24'],
['id' => 'X', 's_id' => 9, 'date' => '2022-03-24'],
['id' => 'X', 's_id' => 10, 'date' => '2022-03-24'],
];

// Initialize an empty array to store the total result
$totalResult = [];

// Loop through the data array
foreach ($data as $row) {
$date = $row['date'];
$s_id = $row['s_id'];

// Check if the date exists in the totalResult array
if (!isset($totalResult[$date])) {
$totalResult[$date] = [];
}

// Check if the s_id exists in the totalResult array for the specific date
if (!isset($totalResult[$date][$s_id])) {
$totalResult[$date][$s_id] = 0;
}

// Increment the total result for the specific s_id and date
$totalResult[$date][$s_id]++;
}

// Output the total result
foreach ($totalResult as $date => $result) {
echo "Date: $date\n";
foreach ($result as $s_id => $total) {
echo "s_id: $s_id, Total: $total\n";
}
echo "\n";
}
?>


This code will calculate the total result for each `s_id` on each date and output the results accordingly. You can replace the sample data with your actual data from the database.

Rate this post

3 of 5 based on 5167 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us