Accessing MySQL Result Set Data with a Foreach Loop
Given a MySQL result set returned as a multidimensional array, it may be used as a result of the mysql_fetch_assoc() function. However, one may encounter difficulties when attempting to iterate through it using a foreach loop.
The key lies in utilizing associative arrays to retrieve the desired data. This method is more efficient than redeclaring foreach loops within each other, which can lead to performance issues.
foreach ($rows as $row) { echo $row['id']; echo $row['firstname']; echo $row['lastname']; }
In this example, the $rows variable represents the multidimensional array containing the result set data. Each iteration of the foreach loop assigns the current row to the $row variable, which is then accessed using associative keys ('id', 'firstname', and 'lastname').
By employing associative arrays, we can simplify the iteration process and efficiently access the required data from the result set.
The above is the detailed content of How do I iterate over a MySQL result set using a foreach loop?. For more information, please follow other related articles on the PHP Chinese website!