Php reads csv data and saves it to an array. Php reading csv data and saving it to an array This article mainly introduces how php reads csv data and saves it to an array. This function is implemented through encapsulated class files, is the method to read csv data from the csv file in php and save it to an array.
This article mainly introduces how php reads csv data and saves it to an array. This function is implemented through encapsulated class files. it is a practical technique for csv file operations. For more information, see
This example describes how php reads csv data and saves it to an array. Share it with you for your reference. The specific analysis is as follows:
Csv is a substitute for commonly used excel formats. in many cases, we export data into csv format, which is no different from excel, the following program is to read csv data and save it to an array. we need to operate on the data, so save it to the data. the code is as follows:
The code is as follows:
$ Info = csvtoarray: open('teste.csv ');
// Echo'
';
//print_r($info);
//echo '
';
Foreach ($ info as $ c)
{
Echo 'student ID: '. $ c [0];
Echo 'name: '. $ c [1];
Echo 'age: '. $ c [2];
Echo 'height: '. $ c [3].'
';
}
Final class csvtoarray {
/**
* Parse the csv file into an array and return it
*
* @ Param string $ file path of the csv file to be parsed
* @ Param char $ delimiter the default content delimiter in the csv file is;
* @ Return array
*/
Public static function open ($ file, $ delimiter = ';'){
Return self: ordenamultiarray (self: csvarray ($ file, $ delimiter), 1 );
}
Private function csvarray ($ file, $ delimiter)
{
$ Result = array ();
$ Size = filesize ($ file) + 1;
$ File = fopen ($ file, 'r ');
$ Keys = fgetcsv ($ file, $ size, $ delimiter );
Fseek ($ file, 0); // The original content does not exist here. add the content of the first line.
While ($ row = fgetcsv ($ file, $ size, $ delimiter ))
{
For ($ I = 0; $ I <count ($ row); $ I ++)
{
If (array_key_exists ($ I, $ keys ))
{
$ Row [$ keys [$ I] = $ row [$ I];
}
}
Print_r ($ row );
$ Result [] = $ row;
}
Fclose ($ file );
Return $ result;
}
Private function ordenamultiarray ($ multiarray, $ secondindex)
{
While (list ($ firstindex,) = each ($ multiarray ))
$ Indexmap [$ firstindex] = $ multiarray [$ firstindex] [$ secondindex];
Asort ($ indexmap );
While (list ($ firstindex,) = each ($ indexmap ))
If (is_numeric ($ firstindex ))
$ Sortedarray [] = $ multiarray [$ firstindex];
Else $ sortedarray [$ firstindex] = $ multiarray [$ firstindex];
Return $ sortedarray;
}
}
I hope this article will help you with php programming.
This article describes how to read csv data from php and save it to an array. This function is implemented through encapsulated class files. it is an implementation of csv file operations...