簡體   English   中英

CSV到php關聯數組

[英]CSV to php associative array

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

這沒有錯誤,但是一個奇怪的數組似乎搞砸了。 有什么想法,我怎么能得到我想要的結構?

這應該工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM