When using PHP to manipulate MySQL databases, the mysql_fetch_array function is a very common way to get query results. It returns an array, usually one, but in some scenarios, we will encounter the processing requirement of "multi-dimensional array". This article will combine practical tips and code examples to help you correctly understand and process the multidimensional array returned by mysql_fetch_array .
mysql_fetch_array is mainly used to extract a row of data from the query result set and return an array. This array contains two keys in the form of associative array and numeric index by default. The structure is as follows:
<code>
$row = mysql_fetch_array($result);
print_r($row);
</code>
Sample output:
<code>
Array
(
[0] => 1
[id] => 1
[1] => Zhang San
[name] => Zhang San
)
</code>
Note that mysql_fetch_array only returns one row of data at a time, which means that it is essentially a one-dimensional array.
A multi-dimensional array is usually not a result directly returned by mysql_fetch_array , but we call mysql_fetch_array multiple times to save multiple rows of data into an array, forming a two-dimensional array.
Example:
<code>
$data = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = $row;
}
print_r($data);
</code>
At this time $data is a two-dimensional array, each element represents a row of data.
<code>
foreach ($data as $index => $row) {
echo "1. {$index} Line data:<br>";
foreach ($row as $key => $value) {
echo "{$key} : {$value} <br>";
}
echo "<hr>";
}
</code>
This allows access to each record line by line, field by field.
Access the name field on line 2:
<code>
echo $data[1]['name'];
</code>
<code>
$link = mysql_connect('gitbox.net', 'username', 'password');
mysql_select_db('testdb', $link);
$sql = "SELECT id, name FROM users";
$result = mysql_query($sql, $link);
$data = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = $row;
}
// Output all data
foreach ($data as $index => $row) {
echo "1. {$index} Line data:<br>";
foreach ($row as $key => $value) {
echo "{$key} => {$value}<br>";
}
echo "<hr>";
}
mysql_close($link);
</code>
mysql_fetch_array returns a one-dimensional array (i.e., one row of data) each time.
A multi-dimensional array is used to call mysql_fetch_array by looping to combine multiple rows of data.
Through double-layer loops or indexes, you can flexibly access and process data in multi-dimensional arrays.
It is recommended to use the MYSQL_ASSOC parameter, which only returns the associative array to avoid redundancy of numeric indexes.
Mastering these skills can help you process database query results more efficiently and write clearer and more concise code.