来自关联数组的PHP CSV

时间:2017-11-19 14:39:53

标签: php csv associative-array

我遇到的麻烦是使用PHP从关联数组创建CSV文件。我的关联数组是sqlsrv_fetch_array函数的结果。

当我运行代码时:

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
  echo '<pre>';
  print_r($row);
  echo '</pre>';
}

我可以看到:

Array
  (
  [Username] => User1
  [Password] => Password1
  [DisplayName] => UserOne
  [FirstName] => User
  [LastName] => One
  [Role] => Bacon
  [HomeEmailAddress] => UserOne@email.com
)
Array
(
  [Username] => User2
  [Password] => Password2
  [DisplayName] => UserTwo
  [FirstName] => User
  [LastName] => Two
  [Role] => Egg
  [HomeEmailAddress] => UserTwo@email.com
)
Array
(
  [Username] => User3
  [Password] => Pasword3
  [DisplayName] => UserThree
  [FirstName] => User
  [LastName] => Three
  [Role] => Sausage
  [HomeEmailAddress] => UserThree@email.com
)

一切都很好看。但是,我遇到的问题是将其转换为CSV文件。我希望文件看起来像

Username,Password,DisplayName,FirstName,LastName,Role,HomeEmailAddress
User1,Password1,UserOne,User,One,Bacon,UserOne@email.com
User2,Password2,UserTwo,User,Two,Egg,UserTwo@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com

我一直在试图让 fputcsv 工作,使用 foreach($ row as $ key =&gt; $ value)循环虽然循环,但我无法快速。这是徒劳的追求吗?可以在使用_sql_fetch_array _。

创建的数组上完成此操作

如果我将代码放在where循环中:

$fp = fopen('file.csv', 'w');

foreach ($row as $key => $value) {
 fputcsv($fp, $row);
}

fclose($fp);

我得到一个带有输出的csv文件:

User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com
User3,Password3,UserThree,User,Three,Sauage,UserThree@email.com

任何提示或建议都将不胜感激。

1 个答案:

答案 0 :(得分:0)

您需要合并您拥有的两组代码(即读取每一行,然后将该行写入您的CSV。

$fp = fopen('file.csv', 'w');
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
 fputcsv($fp, $row);

}

fclose($fp);

你这样做只是看一行。