Home >Backend Development >PHP Tutorial >How to convert MySQL query result array to object?

How to convert MySQL query result array to object?

王林
王林Original
2024-04-29 13:09:011312browse

The method to convert the MySQL query result array into an object is as follows: Create an empty object array. Loop through the resulting array and create a new object for each row. Use a foreach loop to assign the key-value pairs of each row to the corresponding properties of the new object. Adds a new object to the object array. Close the database connection.

如何将 MySQL 查询结果数组转换为对象?

How to convert the MySQL query result array into an object

When using MySQL, the query results are usually returned in the form of an array . However, sometimes it is necessary to convert these arrays into objects so that the data can be more easily manipulated and accessed. This article will show you how to convert a MySQL query result array into an object using PHP.

// 创建一个 MySQL 连接
$conn = new mysqli("localhost", "username", "password", "database");

// 执行一个查询并获取结果
$result = $conn->query("SELECT * FROM users");

// 创建一个空数组来存储对象
$objects = array();

// 循环结果数组并创建对象
while ($row = $result->fetch_assoc()) {
    $object = new stdClass();
    foreach ($row as $key => $value) {
        $object->{$key} = $value;
    }
    $objects[] = $object;
}

// 关闭数据库连接
$conn->close();

// 现在,$objects 数组包含查询结果中的对象。

// 实战案例

//假设我们有一个 users 表,其中包含以下列:
// id, name, email, created_at

// 我们可以使用以下代码将查询结果转换为对象:

// Execute a query and get the results
$result = $conn->query("SELECT * FROM users");

// Create an empty array to store Object
$users = array();

// Loop the result array and create the object
while ($row = $result->fetch_assoc()) {

$user = new stdClass();
$user->id = $row['id'];
$user->name = $row['name'];
$user->email = $row['email'];
$user->created_at = $row['created_at'];
$users[] = $user;

}

// Now, the $users array contains user objects from the users table.

The above is the detailed content of How to convert MySQL query result array to object?. 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