PHP read CSV data saved to array method, CSV array
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:
Copy the Code code 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/936798.html www.bkjia.com true http://www.bkjia.com/PHPjc/936798.html techarticle PHP read CSV data saved to an array of methods, CSV Array This example describes how PHP reads CSV data saved to an array. Share to everyone for your reference. The specific analysis is as follows: CSV is ...