In PHP, we often need to convert table data into arrays. This is a very basic operation, but can get quite tricky if you don't know how to do it. In this article, we will explore how to convert tabular data into an array. We assume that there are 4 columns in the table, namely id, name, age, and gender.
Method 1: Use a For loop to read table data row by row
The first method is to use a For loop to read table data row by row, and then store each row of data into an array. The code is implemented as follows:
<?php // 打开表格文件 $file = fopen('data.csv', 'r'); // 定义结果数组 $result = array(); // 逐行读取数据 while ($data = fgetcsv($file)) { // 将每一行数据存储到数组中 $result[] = array( 'id' => $data[0], 'name' => $data[1], 'age' => $data[2], 'gender' => $data[3] ); } // 关闭文件 fclose($file);
The advantage of this method is that it is easier to understand and the code is relatively simple. But if the table data is relatively large, this method may take up more memory. Because all rows of data need to be stored in an array, it may cause insufficient memory and cause performance problems.
Method 2: Use PHP functions to convert table data into arrays
The second method is to use PHP built-in functions fgetcsv and file to convert the entire table data into arrays. The code is implemented as follows:
<?php // 读取整个表格数据到数组中 $data = file('data.csv'); // 删除第一行表头 unset($data[0]); // 定义结果数组 $result = array(); // 遍历每一行数据 foreach ($data as $line) { // 将每一行数据转化为数组 $row = str_getcsv(trim($line)); // 将每一行数据存储到结果数组中 $result[] = array( 'id' => $row[0], 'name' => $row[1], 'age' => $row[2], 'gender' => $row[3] ); }
The advantage of this method is that there is no need to read table data line by line, and it does not need to occupy a lot of memory, because the entire table data is processed in the file handle memory block.
Conclusion
The above are two methods of converting table data into arrays. Method 1 is more suitable when processing small table data, and method 2 is suitable for processing large table data. In practical applications, we can choose the appropriate method according to the specific situation to ensure efficient processing of data.
The above is the detailed content of How to convert table data into array in php. For more information, please follow other related articles on the PHP Chinese website!