PHP for each function to print td
✔ Recommended Answer
You need to use the years of the first query in the second loop. So first, you change the name of the second $years, such as $categoryYears.
This is my solution. Hope it's useful for you
//....$categoryYears = explode(',', $row['years']);$amounts = explode(',', $row['amounts']);$categories = explode(',', $row['categories']);foreach ($categories as $category) { echo '<tr> <td>' . $category . ' </td>'; //loop for all years of the first query foreach ($years as $key => $year) { //get the index of year in list years of the category if ($yearKey = array_search($year, $categoryYears) !== false) { $amount = isset($amounts[$yearKey]) ? $amounts[$yearKey] : '0'; } else { $amount = '0'; } echo '<td>' . $amount. '</td>'; }//....
Source: stackoverflow.com
Answered By: Khang Tran
To print <td>
elements using a foreach
loop in PHP, you can use the following code:
php<tr>
<?php foreach ($values as $value) { ?>
<td><?php echo $value; ?></td>
<?php } ?>
</tr>
In this example, $values
is an array of values that you want to print in <td>
elements. The foreach
loop iterates over each value in the array and prints a <td>
element with the value using echo
. The code is wrapped in <tr>
tags to create a table row.
You can customize this code to fit your specific needs. For example, you could add additional HTML attributes to the <td>
elements or wrap them in additional HTML tags as needed.
Note that this code assumes that the $values
array contains strings that are safe to output in HTML without modification. If the array contains user input or other data that may contain HTML special characters, you should use htmlspecialchars()
or a similar function to escape the values before outputting them in HTML.
Comments
Post a Comment