2011-11-21 1 views
3

Je connais fgetcsv, mais il ne fait pas vraiment ce que je cherche.PHP CSV à Array d'une manière spécifique

je le fichier csv suivant:

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

Je cherche quelque chose qui va créer un tableau qui ressemble à ceci:

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

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

des idées?

+1

'fgetcsv' vous servira bien dans cette situation. Lisez la première ligne, rassemblez les noms des champs, puis lisez les lignes restantes et collectez-les dans le tableau en utilisant les noms des champs comme clés. – kapa

Répondre

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 Belle utilisation de 'array_combine'. – kapa

0

Essayez quelque chose comme ceci:

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

Vous devez écrire votre propre fonction pour cela. Il a toutes sortes d'exigences implicites telles que la première ligne étant les indices clés. Si c'est ce que vous voulez toujours vous pouvez faire:

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); 
} 

Donner le résultat de:

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