I'm trying to fill table with values which I'm getting from the database but when I loop though array some values are getting out of the table.
In above output vertical months are registered users count and horizontal rows are their activity.
Example:
In vertical January month 1563 users are registered, in same row horizontal January has 1563 because registration will count as their activity. In same row July month 13 users are active out of 1563 registered users and same goes on for other months of same row.
I'm getting values in expected tds but want to remove extra generated td (Marked in red box).
CodePudding user response:
You’ve got one too many for
loops, the innermost foreach
isn’t needed. In fact, because you are working with data that is constrained to known values that must exist in a specific order, you shouldn’t even trust it.
Because you have a database, are dealing with JSON inside an array, and have a lot of data, it is unfortunately hard to reproduce your code. Instead, I’ve made a simple array that mimics your database with the JSON already decoded, but hopefully it makes sense still.
I usually comment my code more but I think it mostly speaks relative to your code. One major change I added was to use ??
which can make missing array items much easier to read. One known potential bug is if the dates coming out of the database aren’t in the correct order this will render strangely.
$data = [
['month' => 'Jan', 'year' => 2022, 'data' => ['Jan' => 1563, 'Mar' => 6]],
['month' => 'Feb', 'year' => 2022, 'data' => ['Feb' => 345, 'Mar' => 76, 'May' => 8]],
];
for($row = 1; $row <= 12; $row ){
$monthNameLong = date('F', mktime(0, 0, 0, $row, 1, date('Y')));
$monthNameShort = date('M', strtotime("2022-$row-01"));
echo '<tr>';
printf('<td>%1$s</td>', $monthNameLong);
if(($data[$row - 1]['month'] ?? null) === $monthNameShort && isset($data[$row - 1]['data'][$monthNameShort])){
$total = $data[$row - 1]['data'][$monthNameShort];
} else {
$total = '';
}
printf('<td>%1$s</td>', $total);
for($col = 1; $col <= 12; $col ){
$colMonthNameShort = date('M', strtotime("2022-$col-01"));
printf('<td>%1$s</td>', $data[$row - 1]['data'][$colMonthNameShort] ?? 0);
}
echo '</tr>';
echo PHP_EOL;
}
Demo: https://3v4l.org/JecP1