2011-11-21 50 views
3

我知道fgetcsv,但它并没有真正做我正在寻找的东西。以特定的方式将PHP CSV格式化为数组

我有以下csv文件:

productId,productName,productActive 
1,test product,1 
2,test product2,0 

我正在寻找的东西,将创建一个数组,看起来像这样:

array (0) 
    ['productId'] => 1 
    ['productName'] => test product 
    ['productActive'] => 1 

array (1) 
    ['productId'] => 2 
    ['productName'] => test product2 
    ['productActive'] => 0 

什么想法?

+1

'fgetcsv'将有助于你在这种情况下。阅读第一行,收集字段名称,然后读取其余行,并使用字段名称作为关键字将它们收集到数组中。 – kapa

回答

7
// open the file. 
if (($handle = fopen("in.csv", "r")) !== FALSE) { 
     // read the column headers in an array. 
     $head = fgetcsv($handle, 1000, ","); 

     // read the actual data. 
     while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { 

       // create a new array with the elements in $head as keys 
       // and elements in array $data as values. 
       $combined = array_combine($head,$data); 

       // print. 
       var_dump($combined); 
     } 
     // done using the file..close it, 
     fclose($handle); 
} 

See it

+2

+1 Nice'array_combine'用法。 – kapa

0

尝试这样:

$rows = array(); 
$headers = fgetcsv($file); 
while($line = fgetcsv($file)) { 
    $row = array(); 
    foreach($line as $key => $value) { 
     $row[$headers[$key]] = $value; 
    } 
    $rows[] = $row; 
} 
0

你将不得不写你自己的功能。它有各种隐含的要求,如第一行是关键指标。如果这就是你总是想,那么你可以这样做:

if (($handle = fopen("test.csv", "r")) !== FALSE) { 
    $row_headers = fgetcsv($handle); 
    $output = array(); 

    //don't specify a limit to the line length (i.e. 1000). 
    //just grab the whole line 
    while (($data = fgetcsv($handle)) !== FALSE) { 
     $num = count($data); 
     $row++; 
     $row_array = array(); 
     //For each column, create a row array with the index being 
     //the column heading and the data being the row data. 
     for ($c=0; $c < $num; $c++) { 
      $row_array[$row_headers[$c]] = $data[$c]; 
     } 

     //Add each row to the output 
     $output[] = $row_array; 
    } 
    print_r($output); 
} 

给予的结果:

Array ([0] => Array ([productId] => 1 [productName] => test product [productActive] => 1) [1] => Array ([productId] => 2 [productName] => test product2 [productActive] => 0))