Home  >  Article  >  Backend Development  >  PHP reads csv data and saves it to array code_PHP tutorial

PHP reads csv data and saves it to array code_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:08:23755browse

PHP reads csv data and saves it to the array code. csv is a replacement for the commonly used excel format. Many times when we export data, it will be exported to csv format. This is no different from excel. The following program is to read the csv data and save it to We want to operate on the array, so we save it to the data.

php tutorial to read csv data and save it to array code
csv is a replacement for the commonly used excel format. Many times when we export data, it will be exported to 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.

$info=csvtoarray::open('teste.csv');
//echo '

';<br>//print_r($info);<br>//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 The path of the csv file to be parsed
* @param char $delimiter The content delimiter in the csv file defaults to;
* @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);//There is no original one here..Add it yourself...so that you can read 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;
}
}


www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/444895.htmlTechArticlephp reads csv data and saves it to array code csv is a replacement for the commonly used excel format. Many times we export The data will be exported into csv format, which is no different from excel. The following...
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