php read csv data saved to the array code

Source: Internet
Author: User
Keywords Network programming PHP tutorial
Tags array code csv data difference echo export file

php tutorial read csv data saved to the array code
csv is commonly used alternatives to excel format Oh, many times we export data will result in csv format, and no difference between excel, the following program is to read csv data saved to the array we want to operate on the data, so Save to data.

$ info = csvtoarray :: open ('teste.csv');
// echo '<pre>';
// print_r ($ info);
// echo '</ pre>';
foreach ($ info as $ c)
{
echo 'Student ID:'. $ c [0];
echo 'name:'. $ c [1];
echo 'Age:'. $ c [2];
echo 'Height:'. $ c [3]. '<br>';
}

final class csvtoarray {

/ **
Parse the csv file as an array
*
* @param string $ file The path to the csv file to parse
* @ param char $ delimiter csv file content delimiter 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); / / Here's not .. their own plus .. This can 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;
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.