Home  >  Article  >  Backend Development  >  How to convert query results into an array through PHP

How to convert query results into an array through PHP

PHPz
PHPzOriginal
2023-03-31 09:05:11737browse

In PHP, the results of querying the MySQL database are usually returned in the form of an associative array or a numeric array. However, sometimes we want to process the query results in the form of an array. This article will introduce how to convert query results into an array through PHP.

1. Query MySQL data

First we need to connect to the MySQL database in PHP and perform data query operations. The following is a simple query example:

// 假设我们已经连接到了MySQL数据库,$mysqli是一个mysqli对象
$query = "SELECT * FROM users";
$result = $mysqli->query($query);

The above code will query all records from a table named "users" and save the results in the $result variable.

2. Convert to associative array

We can use the fetch_assoc() method to convert the query results into an associative array, where the key name is the field name in the query result. For example:

// 转换为关联数组
$rows = array();
while($row = $result->fetch_assoc()) {
    $rows[] = $row;
}

// 打印结果
var_dump($rows);

The above code converts the query results into an associative array and saves it in the $rows variable. Get each row of data through a loop and add it to the $rows array, and finally print the results out through the var_dump() function.

3. Convert to numeric array

We can also convert the query results into a numeric array, where the key name starts with 0. This requires the fetch_row() method. The sample code is as follows:

// 转换为数字数组
$rows = array();
while($row = $result->fetch_row()) {
    $rows[] = $row;
}

// 打印结果
var_dump($rows);

The above code converts the query results into a numeric array and saves it in the $rows variable. Get each row of data through a loop and add it to the $rows array, and finally print the results out through the var_dump() function.

4. Summary

This article introduces how to convert MySQL query results into an array through PHP. We can use the fetch_assoc() method to convert the result into an associative array or we can use the fetch_row() method to convert the result into a numeric array. Use these methods to easily process query results and perform subsequent operations.

The above is the detailed content of How to convert query results into an array through PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn