1

我的 CSV 文件具有这种结构

title;firstName;lastName;email;
Sir;Bob;Public;bob.p@gmail.com;

第一行显示列名。内容从第二行开始。现在我希望将它放入这样的关联数组中

array([0] => 
            array(
                   'title' => 'Sir', 
                   'firstName' => 'Bob', 
                   'lastName' => 'Public', 
                   'email' => 'bob.q@gmail.com'
            ) 
)

我尝试了什么:

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

这没有给出错误,而是一个似乎被搞砸的奇怪数组。有什么想法可以得到我想要的结构吗?

4

2 回答 2

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);    
}
于 2013-01-08T13:00:29.073 回答
0
$entities = array();
//Assuming you are able to get proper array from CSV
$data = array('title;firstName;lastName;email;', 'Sir;Bob;Public;bob.p@gmail.com;');
$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;
}
于 2013-01-08T13:23:07.693 回答