How to convert records into array in PHP
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; }
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:
- 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);
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.
- 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);
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:
- 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);
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.
- Convert a string into an array
$str = 'a,b,c,d,e'; // 将$str字符串按,分割成数组 $arr = explode(',', $str); print_r($arr);
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.
- Convert the array into a string
$arr = array('a', 'b', 'c', 'd', 'e'); // 将$arr数组合并成一个字符串,元素之间用,分隔 $str = implode(',', $arr); echo $str;
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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.

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.

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.

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

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

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

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