PHP read in specific csv file column as an array

妖精的绣舞 提交于 2019-12-05 22:21:14

fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:

$data = array();
while($row = fgetcsv($file)) {
   $data[] = $row;
}

The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:

   $data[] = $row[1];

However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:

   $data[$row[0]] = $row[1];

and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.

$csv = array_map("str_getcsv", file("data.csv", "r")); 
$header = array_shift($csv); 
// Seperate the header from data

$col = array_search("Value", $header); 
 foreach ($csv as $row) {      
 $array[] = $row[$col]; 
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
    $rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
    $i = 0;
    foreach ($members as $mem) {
        $membersArray[ $i ][ ] = $mem;
        $i++;
    }
}

$newArray = array_combine($header, array_map("array_filter",$membersArray));

You can also use this class http://code.google.com/p/php-csv-parser/

<?php

require_once 'File/CSV/DataSource.php';

$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());

?>
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!