Home >Backend Development >PHP Problem >How to convert php table to two-dimensional array

How to convert php table to two-dimensional array

PHPz
PHPzOriginal
2023-04-20 09:08:01663browse

In PHP, tables are one of the common data formats. We usually need to process the data in the tables, such as filtering, sorting, etc. At this point, converting the table into a two-dimensional array is a good choice, because arrays are one of the most flexible and efficient data structures in PHP.

So, how to convert a table into a two-dimensional array in PHP? Let’s introduce it in detail below.

  1. Use the PHP built-in function fgetcsv() to parse the table in CSV format

The table in CSV (Comma-Separated Values) format separates each row with commas. End with newline character. We can use PHP's built-in function fgetcsv() to read each row of data in the CSV table and convert it into array form. The following is a simple sample code:

$handle = fopen("data.csv", "r");
$data = [];
while (($row = fgetcsv($handle)) !== false) {
    $data[] = $row;
}
fclose($handle);

In the above code, the data source file is first opened through the fopen() function, and then the table data in the data source file is read line by line through the while loop. Each row is parsed using the fgetcsv() function, and the parsed data is stored in the $data array in the form of an array. Finally close the data source file.

  1. Use the PHPExcel library to parse tables in Excel format

If you need to process tables in Excel format, you can use the PHPExcel library to convert tables into two-dimensional arrays. The PHPExcel library is a PHP open source class library that can operate a variety of spreadsheet formats, such as Excel, CSV, etc.

The following is a simple sample code:

require_once 'PHPExcel/IOFactory.php';
$excel = PHPExcel_IOFactory::load("data.xlsx");
$data = array();
$sheet = $excel->getActiveSheet();
foreach ($sheet->getRowIterator() as $rowKey => $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);
    $temp = array();
    foreach ($cellIterator as $cellKey => $cell) {
        $temp[] = $cell->getValue();
    }
    $data[] = $temp;
}

In the above code, first introduce the PHPExcel library, load the Excel data source file, and use the getRowIterator() function to get the data for each row, and then use the getCellIterator() function to get the data for each cell in each row. Finally, each row of data is stored in a two-dimensional array for subsequent data processing and operations.

  1. Data format conversion function

In addition to the above two methods, we can also use custom data conversion functions to complete the conversion from tables to two-dimensional arrays. This method requires different processing according to different table formats, which is relatively cumbersome, but it can flexibly control the data format conversion process. The following is a simple sample code:

function table2array($table, $headerIndex = 0, $skipEmptyRow = true, $intval = true)
{
    $rows = explode("\n", $table);
    $header = array();
    $data = array();
    foreach ($rows as $key => $row) {
        if ($skipEmptyRow && trim($row) == '') {
            continue;
        }
        if ($headerIndex == $key) {
            $header = explode("\t", $row);
            continue;
        }
        $cols = explode("\t", $row);
        $rowData = array();
        foreach ($cols as $col) {
            if ($intval && is_numeric($col)) {
                $rowData[] = intval($col);
            } else {
                $rowData[] = $col;
            }
        }
        $data[] = array_combine($header, $rowData);
    }
    return $data;
}

In the above code, we convert table data into a two-dimensional array through a custom function. Function parameters include:

  • $table: table data, format is string.
  • $headerIndex: The index of the row where the header is located, the default is 0.
  • $skipEmptyRow: Whether to ignore empty lines, the default is true.
  • $intval: Whether to convert numbers into integers, the default is true.

Inside the function, first use the explode() function to split the string into an array form according to the specified delimiter, and then convert and assemble the data type. Finally, each row of data is stored in the $data array in the form of an associative array, and this two-dimensional array is returned.

Summary

This article introduces three common ways to convert tables into two-dimensional arrays. Among them, the fgetcsv() function is suitable for CSV format, the PHPExcel library is suitable for Excel format, and the custom data conversion function is suitable for tables in other formats. In actual development, we can flexibly choose the method suitable for our own scenarios as needed.

The above is the detailed content of How to convert php table to two-dimensional array. 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