PHP read CSV data saved to array method
This article mainly describes the PHP read CSV data saved to the array method, through the encapsulated class file implementation of this function, is the operation of the CSV file practical skills, the need for friends can refer to the following
The example in this article describes how PHP reads CSV data to an array. Share to everyone for your reference. The specific analysis is as follows:
CSV is a common alternative to excel format, many times we export data will be in CSV format, so and Excel no difference, the following program is to read the CSV data saved to the array we want to manipulate the data, so save to the data, the code is as follows:
The code is as follows:
$info =csvtoarray::open (' teste.csv ');
Echo '
Echo '
';
foreach ($info as $c)
{
Echo ' Study number: '. $c [0];
Echo ' name: '. $c [1];
Echo ' Age: '. $c [2];
echo ' Height: '. $c [3]. '
';
}
Final class csvtoarray{
/**
* Parse the CSV file into an array to return
*
* @param string $file The path to the CSV file to parse
* @param char $delimiter the contents of the CSV file are separated defaults think;
* @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);//Here the original is not. Add yourself. This will read the contents 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 is helpful to everyone's PHP programming.
http://www.bkjia.com/PHPjc/975891.html www.bkjia.com true http://www.bkjia.com/PHPjc/975891.html techarticle PHP read CSV data saved to an array method this article mainly introduces the method that PHP reads CSV data to the array, realizes this function through the encapsulated class file, it is the real of the operation of CSV file ...