In PHP, what is the difference between a multidimensional array and a single-dimensional array when storing and accessing data retrieved from a MySQL database?
When storing and accessing data retrieved from a MySQL database in PHP, a multidimensional array is useful when dealing with multiple rows of data, where each row contains multiple columns. This allows for organizing the data in a structured way for easier manipulation. On the other hand, a single-dimensional array is suitable for storing data from a single row or a single column of the database.
// Storing data retrieved from a MySQL database in a multidimensional array
$data = [];
while ($row = $result->fetch_assoc()) {
$data[] = $row;
}
// Accessing data from a multidimensional array
foreach ($data as $row) {
echo $row['column_name'];
}
// Storing data retrieved from a MySQL database in a single-dimensional array
$data = [];
while ($row = $result->fetch_array()) {
$data[] = $row['column_name'];
}
// Accessing data from a single-dimensional array
foreach ($data as $value) {
echo $value;
}