Home Backend Development PHP Problem How to convert records into array in PHP

How to convert records into array in PHP

Apr 25, 2023 pm 05:29 PM

In PHP development, we often need to convert records into arrays to facilitate data reading and processing. How to convert records into array in PHP? This article will introduce several methods for your reference.

1. Use loops to convert records into arrays

When using PHP for database operations, the query result is usually a recordset object. Each record contains multiple field values. We can loop through Iterate over the recordset object, convert each record into an array, and add it to the resulting array. The specific code is as follows:

// 查询语句
$sql = "SELECT * FROM users WHERE status=1";
// 执行查询
$result = mysqli_query($conn, $sql);
// 定义结果数组
$data = array();
// 遍历记录集对象,将每条记录转换成数组
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}
Copy after login

In the above code, we first define a query statement and execute the query through the mysqli_query function. Then an empty result array $data is defined, and then the recordset object is traversed through a while loop, each record is converted into an array, and added to the result array through $data[] = $row. Finally we get a $data array, where each element is an array converted from records.

2. Use the functions provided by PHP to convert records into arrays

In addition to writing your own conversion code, PHP also provides some powerful functions that can easily convert records into arrays. The following are commonly used functions:

  1. mysqli_fetch_all function

The mysqli_fetch_all function can convert the entire record set into a two-dimensional array at one time. The specific code is as follows:

// 查询语句
$sql = "SELECT * FROM users WHERE status=1";
// 执行查询
$result = mysqli_query($conn, $sql);
// 将整个记录集转换成二维数组
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
Copy after login

In the above code, we called the mysqli_fetch_all function and specified the second parameter as MYSQLI_ASSOC, which means that the result is returned in the form of an associative array. Finally, we get a $data array, where each element is an array converted from a record.

  1. pdo’s fetchAll function

If you use PDO to operate the database, you can use the fetchAll function of the PDOStatement object to convert the records into an array. The specific code is as follows:

// 查询语句
$sql = "SELECT * FROM users WHERE status=1";
// 执行查询
$stmt = $pdo->query($sql);
// 将整个记录集转换成数组
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
Copy after login

In the above code, we first define a query statement and execute the query through the $pdo->query function. Then call the $stmt->fetchAll function and specify the parameter as PDO::FETCH_ASSOC, which means that the result will be returned in the form of an associative array. Finally, we get a $data array, where each element is an array converted from a record.

3. Use PHP to convert arrays

In addition to converting records into arrays, you can also convert arrays. PHP provides a variety of functions for converting arrays. For example, the implode function can convert an array into a string, the explode function can convert a string into an array, and the array_column function can extract a column from a two-dimensional array to form a one-dimensional array. wait. The following are some examples:

  1. Extract a column from a two-dimensional array to form a one-dimensional array
$arr = array(
    array('id' => 1, 'name' => '张三'),
    array('id' => 2, 'name' => '李四'),
    array('id' => 3, 'name' => '王五')
);
// 提取出id列形成一维数组
$ids = array_column($arr, 'id');
print_r($ids);
Copy after login

In the above code, we define a two-dimensional array$ arr contains several arrays, each array contains two key-value pairs, id and name. Then use the array_column function, specifying the second parameter as 'id', which means to extract the values ​​of the 'id' key-value pairs in all sub-arrays in $arr to form a one-dimensional array $ids.

  1. Convert a string into an array
$str = 'a,b,c,d,e';
// 将$str字符串按,分割成数组
$arr = explode(',', $str);
print_r($arr);
Copy after login

In the above code, we define a string $str, which contains several elements separated by commas. Then use the explode function to split the $str string into an array $arr by commas.

  1. Convert the array into a string
$arr = array('a', 'b', 'c', 'd', 'e');
// 将$arr数组合并成一个字符串,元素之间用,分隔
$str = implode(',', $arr);
echo $str;
Copy after login

In the above code, we define an array $arr, which contains several elements. Then use the implode function to merge the elements in the $arr array into a string $str, with commas separating the elements.

4. Summary

Converting records into arrays is a very common thing in PHP. This article introduces several methods, including loop conversion, conversion using functions, array conversion, etc. Different methods have different advantages and disadvantages, and can be chosen according to specific scenarios.

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

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

PHP API Rate Limiting: Implementation strategies. PHP API Rate Limiting: Implementation strategies. Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

See all articles