What are the best practices for organizing and manipulating data from an array before displaying it in a table in PHP?
When organizing and manipulating data from an array before displaying it in a table in PHP, it is important to properly structure the data to ensure it is displayed correctly. One common approach is to loop through the array and extract the necessary information into a new array or object that can be easily displayed in a table format. Additionally, you may need to apply sorting, filtering, or formatting functions to the data before displaying it in the table.
// Sample array of data
$data = [
['id' => 1, 'name' => 'John Doe', 'age' => 30],
['id' => 2, 'name' => 'Jane Smith', 'age' => 25],
['id' => 3, 'name' => 'Alice Johnson', 'age' => 35]
];
// Extracting necessary information into a new array
$tableData = [];
foreach ($data as $row) {
$tableData[] = [
'ID' => $row['id'],
'Name' => $row['name'],
'Age' => $row['age']
];
}
// Displaying data in a table
echo '<table>';
echo '<tr><th>ID</th><th>Name</th><th>Age</th></tr>';
foreach ($tableData as $row) {
echo '<tr>';
echo '<td>' . $row['ID'] . '</td>';
echo '<td>' . $row['Name'] . '</td>';
echo '<td>' . $row['Age'] . '</td>';
echo '</tr>';
}
echo '</table>';