【问题标题】:CSV to php associative arrayCSV 到 php 关联数组
【发布时间】:2012-12-22 07:56:24
【问题描述】:

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

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

【问题讨论】:

  • 您有一个; 分隔文件,但您指定, 作为分隔符。
  • 谢谢,我编辑了我的问题
  • CSV to Associative Array的可能重复

标签: php arrays multidimensional-array


【解决方案1】:

这应该可行:

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

【讨论】:

  • 这不起作用。 Header 是一个大字符串,所有列标题都用“,”分隔。它不会从我的问题中产生结构。
  • 您问题中的 CSV 使用了;。更改我的代码中的分隔符以匹配 CSV 中使用的分隔符。
  • 谢谢,这就是问题所在。奇怪的事情,但是用 ',' 就可以了
【解决方案2】:
$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;
}

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 2015-07-16
    相关资源
    最近更新 更多