2013-01-08 126 views
1

我的CSV文件具有这种结构CSV到PHP关联数组

title;firstName;lastName;email; 
Sir;Bob;Public;[email protected]; 

第一行显示的列名。内容从第二行开始。现在,我想这放入关联数组这样

array([0] => 
      array(
        'title' => 'Sir', 
        'firstName' => 'Bob', 
        'lastName' => 'Public', 
        'email' => '[email protected]' 
      ) 
) 

我试了一下:

$entities = array(); 

    while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) { 

     $num = count($data); 

     for ($c = 0; $c < $num; $c++) { 

       $line = array(); 
       //save first row 
       if ($row == 1) { 
        foreach (explode(';', $data[$c]) as $field) { 
         //dont save empty fields 
         if ($field != "") { 
         $fields[] = $field; 
         $line[$field] = array(); 
         } 
        } 
       } 
       //go through contents and save them 
       foreach ($fields as $field) { 
        for ($i = 2; $i < count($fields); $i++) { 
         $cust = explode(";", $data[$c]); 
         $line[$field][] = $cust[$i]; 
        } 
       } 
       $entities[] = $line; 
       $row++; 
      } 
     } 

     fclose($handle); 
    } 

这给没有错误,但是,这似乎是搞砸了一个怪阵。任何想法如何能得到我想要的结构?

+3

你有一个';'分隔的文件还没有要指定的','作为分隔符。 –

+0

谢谢,我编辑了我的问题 –

+0

[CSV到关联数组]的可能重复(http://stackoverflow.com/questions/4801895/csv-to-associative-array) – ManseUK

回答

4

这应该工作:

$entities = array(); 
$header = fgetcsv($handle, 0, ";"); // save the header 
while (($values = fgetcsv($handle, 0, ";")) !== FALSE) { 
    // array_combine 
    // Creates an array by using one array for keys and another for its values 
    $entities[] = array_combine($header, $values);  
} 
+0

这不起作用。标题是一个大字符串,所有列标题都用','分隔。它不会产生我的问题的结构。 –

+0

您问题中的CSV使用';'。更改我的代码中的分隔符以匹配CSV中使用的分隔符。 –

+0

http://dpaste.com/867987/这是输出 –

0
$entities = array(); 
//Assuming you are able to get proper array from CSV 
$data = array('title;firstName;lastName;email;', 'Sir;Bob;Public;[email protected];'); 
$num = count($data); 

for ($c = 0; $c < $num; $c++) { 

$line = array(); 
//save first row 

foreach (explode(';', $data[$c]) as $field) { 
    //dont save empty fields 
    if ($c == 0) { 
     if ($field != "") { 
      $fields[] = $field; 
      //$line[$field] = array(); 
     } 
    } else { 
     if ($field != "") { 
      $line[$field] = $field; 
     } 
    } 

} 
if (count($line) > 0) 
    $entities[] = $line; 
}