The error PHP Notice: Undefined index: September occurs because the array key for the month (e.g., "September") does not exist when you attempt to increment its value with $month[$date][ucwords($field[0])] += $field[1];. This is because in PHP, you cannot increment a value in an array if the key for that value does not yet exist.
Final Solution:
php
foreach ($query as $key) {
$key = get_object_vars($key);
$date = date("F", strtotime($key['date']));
$donation = explode(';', $key['donation']);
$d = explode("-", $key['date']);
$num_of_month[] = "$d[0]-$d[1]";
// Initialize month array if not set
if (!isset($month[$date])) {
$month[$date] = array();
}
foreach ($donation as $field) {
$field = explode('=', $field);
if (count($field) > 1 && $field[1]) {
$fieldName = ucwords($field[0]);
// Initialize field in month array if not set, then add value
$month[$date][$fieldName] = ($month[$date][$fieldName] ?? 0) + floatval($field[1]);
}
}
}
Key Changes:
Initialization of Month Array: Before accessing $month[$date], we check if it's set. If not, we initialize it as an empty array.
Initialization and Addition of Field Value: For each donation field, we ensure the field name is set in the $month[$date] array. We use the null coalescing operator (?? 0) to provide a default value of 0 if the key doesn't exist, then add the field's value to it.
Validation of Field Array: We validate that $field has more than one element and that $field[1] is truthy before attempting to use it. This prevents potential notices if the donation string is malformed.
Type Casting for Numeric Values: We explicitly cast $field[1] to a float using floatval() to ensure that the addition operation works correctly, even if the value is initially a string.